diff --git a/README.md b/README.md index b044f291b0..9b578c0a4a 100644 --- a/README.md +++ b/README.md @@ -714,7 +714,7 @@ Every service links to its own page with a coverage breakdown — audited operat | Service | Parity | PARITY Entries | Notes | |---|---|---|---| | [ECR](services/ecr/README.md) | A | 58 | 2 structural gaps; 2 deferred | -| [ECS](services/ecs/README.md) | A | 65 | 5 gaps; 5 structural gaps | +| [ECS](services/ecs/README.md) | A | 65 | 4 gaps; 5 structural gaps | | [EKS](services/eks/README.md) | A | 71 | 5 structural gaps; 1 deferred | ### Storage @@ -899,7 +899,7 @@ Every service links to its own page with a coverage breakdown — audited operat | [SageMaker](services/sagemaker/README.md) | A | 70 | 19 structural gaps | | [SageMaker Runtime](services/sagemakerruntime/README.md) | A | 3 | 1 structural gap | | [Textract](services/textract/README.md) | A | 25 | 2 structural gaps; 1 deferred | -| [Transcribe](services/transcribe/README.md) | A | 44 | 5 gaps; 2 structural gaps | +| [Transcribe](services/transcribe/README.md) | A | 44 | 6 gaps; 2 structural gaps | | [Translate](services/translate/README.md) | A | 19 | 2 structural gaps | ### Media diff --git a/desktop/go.mod b/desktop/go.mod index c8c24fccd9..71f08d440a 100644 --- a/desktop/go.mod +++ b/desktop/go.mod @@ -179,19 +179,26 @@ require ( github.com/gorilla/mux v1.8.1 // indirect github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect + github.com/hajimehoshi/go-mp3 v0.3.4 // indirect github.com/hashicorp/golang-lru/arc/v2 v2.0.7 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/icza/bitio v1.1.0 // indirect github.com/iskorotkov/avro/v2 v2.35.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.11.0 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/jfreymuth/oggvorbis v1.0.5 // indirect + github.com/jfreymuth/vorbis v1.0.2 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/compress v1.20.3 // indirect github.com/kr/fs v0.1.0 // indirect github.com/labstack/echo/v5 v5.4.1 // indirect github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mewkiz/flac v1.0.14 // indirect + github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d // indirect + github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 // indirect github.com/microsoft/go-mssqldb v1.11.2 // indirect github.com/miekg/dns v1.1.73 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect diff --git a/desktop/go.sum b/desktop/go.sum index 93a9cbe81c..81f8e5bf90 100644 --- a/desktop/go.sum +++ b/desktop/go.sum @@ -850,12 +850,19 @@ github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5T github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ= github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo= +github.com/hajimehoshi/go-mp3 v0.3.4 h1:NUP7pBYH8OguP4diaTZ9wJbUbk3tC0KlfzsEpWmYj68= +github.com/hajimehoshi/go-mp3 v0.3.4/go.mod h1:fRtZraRFcWb0pu7ok0LqyFhCUrPeMsGRSVop0eemFmo= +github.com/hajimehoshi/oto/v2 v2.3.1/go.mod h1:seWLbgHH7AyUMYKfKYT9pg7PhUu9/SisyJvNTT+ASQo= github.com/hashicorp/golang-lru/arc/v2 v2.0.7 h1:QxkVTxwColcduO+LP7eJO56r2hFiG8zEbfAAzRv52KQ= github.com/hashicorp/golang-lru/arc/v2 v2.0.7/go.mod h1:Pe7gBlGdc8clY5LJ0LpJXMt5AmgmWNH1g+oFFVUHOEc= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/icza/bitio v1.1.0 h1:ysX4vtldjdi3Ygai5m1cWy4oLkhWTAi+SyO6HC8L9T0= +github.com/icza/bitio v1.1.0/go.mod h1:0jGnlLAx8MKMr9VGnn/4YrvZiprkvBelsVIbA9Jjr9A= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6 h1:8UsGZ2rr2ksmEru6lToqnXgA8Mz1DP11X4zSJ159C3k= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6/go.mod h1:xQig96I1VNBDIWGCdTt54nHt6EeI639SmHycLYL7FkA= github.com/iskorotkov/avro/v2 v2.35.0 h1:UJoOjHeInrzB09APUZP28nJxyWeKenrPctDVx3VS3C4= github.com/iskorotkov/avro/v2 v2.35.0/go.mod h1:msR3h6CL3GwE4r6s8LgN1dUUHlm8mHx8tVvCZF8H5Xo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -866,6 +873,10 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jfreymuth/oggvorbis v1.0.5 h1:u+Ck+R0eLSRhgq8WTmffYnrVtSztJcYrl588DM4e3kQ= +github.com/jfreymuth/oggvorbis v1.0.5/go.mod h1:1U4pqWmghcoVsCJJ4fRBKv9peUJMBHixthRlBeD6uII= +github.com/jfreymuth/vorbis v1.0.2 h1:m1xH6+ZI4thH927pgKD8JOH4eaGRm18rEE9/0WKjvNE= +github.com/jfreymuth/vorbis v1.0.2/go.mod h1:DoftRo4AznKnShRl1GxiTFCseHr4zR9BN3TWXyuzrqQ= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -901,6 +912,12 @@ github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiA github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mewkiz/flac v1.0.14 h1:hyRGAM8NCKznoPmIi9zz2jyO+nfmxY2ErqBnHZ+gxh4= +github.com/mewkiz/flac v1.0.14/go.mod h1:HfPYDA+oxjyuqMu2V+cyKcxF51KM6incpw5eZXmfA6k= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d h1:IL2tii4jXLdhCeQN69HNzYYW1kl0meSG0wt5+sLwszU= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d/go.mod h1:SIpumAnUWSy0q9RzKD3pyH3g1t5vdawUAPcW5tQrUtI= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 h1:h8O1byDZ1uk6RUXMhj1QJU3VXFKXHDZxr4TXRPGeBa8= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985/go.mod h1:uiPmbdUbdt1NkGApKl7htQjZ8S7XaGUAVulJUJ9v6q4= github.com/microsoft/go-mssqldb v1.11.2 h1:FCgeBIK8um2+X4tbun6Q71N1KsfyCDPKY41e1yGVjSE= github.com/microsoft/go-mssqldb v1.11.2/go.mod h1:CYgwG5AMXFojbjTg+GNP5G/y6uz1BhTyZaPqQWzkGnQ= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= @@ -1195,6 +1212,7 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/go.mod b/go.mod index 9453e87780..50002548ef 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.27.3 require ( cel.dev/cel-go v0.33.2 + cloud.google.com/go v0.123.0 cloud.google.com/go/apigateway v1.17.0 cloud.google.com/go/artifactregistry v1.27.0 cloud.google.com/go/batch v1.24.1 @@ -309,10 +310,13 @@ require ( github.com/google/uuid v1.6.0 github.com/googleapis/gax-go/v2 v2.27.0 github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 + github.com/hajimehoshi/go-mp3 v0.3.4 github.com/iskorotkov/avro/v2 v2.35.0 github.com/jackc/pgx/v5 v5.11.0 + github.com/jfreymuth/oggvorbis v1.0.5 github.com/klauspost/compress v1.20.3 github.com/labstack/echo/v5 v5.4.1 + github.com/mewkiz/flac v1.0.14 github.com/microsoft/go-mssqldb v1.11.2 github.com/miekg/dns v1.1.73 github.com/moby/moby/api v1.56.1 @@ -363,7 +367,6 @@ require ( require ( cel.dev/expr v0.25.2 // indirect - cloud.google.com/go v0.123.0 // indirect cloud.google.com/go/auth v0.24.1 // indirect cloud.google.com/go/auth/oauth2adapt v0.3.0 // indirect cloud.google.com/go/compute/metadata v0.10.0 // indirect @@ -469,9 +472,11 @@ require ( github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 // indirect github.com/hashicorp/golang-lru/arc/v2 v2.0.7 // indirect github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/icza/bitio v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.3 // indirect + github.com/jfreymuth/vorbis v1.0.2 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.4.0 // indirect @@ -482,6 +487,8 @@ require ( github.com/magiconair/properties v1.18.12 // indirect github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.24 // indirect + github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d // indirect + github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/go-archive v0.3.3 // indirect github.com/moby/patternmatcher v0.6.1 // indirect diff --git a/go.sum b/go.sum index 2ee625a918..cc038bd0f6 100644 --- a/go.sum +++ b/go.sum @@ -935,12 +935,19 @@ github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 h1:JeSE6pjso5T github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674/go.mod h1:r4w70xmWCQKmi1ONH4KIaBptdivuRPyosB9RmPlGEwA= github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0 h1:Bd7KaOxzULLxtZ/K5s1aLbWhR0+5RToO65TXHsf3bqQ= github.com/grpc-ecosystem/grpc-gateway/v2 v2.31.0/go.mod h1:nN7ts3dFXKtCZWc//yfkpcQNKJABg16/uDVAZpLDalo= +github.com/hajimehoshi/go-mp3 v0.3.4 h1:NUP7pBYH8OguP4diaTZ9wJbUbk3tC0KlfzsEpWmYj68= +github.com/hajimehoshi/go-mp3 v0.3.4/go.mod h1:fRtZraRFcWb0pu7ok0LqyFhCUrPeMsGRSVop0eemFmo= +github.com/hajimehoshi/oto/v2 v2.3.1/go.mod h1:seWLbgHH7AyUMYKfKYT9pg7PhUu9/SisyJvNTT+ASQo= github.com/hashicorp/golang-lru/arc/v2 v2.0.7 h1:QxkVTxwColcduO+LP7eJO56r2hFiG8zEbfAAzRv52KQ= github.com/hashicorp/golang-lru/arc/v2 v2.0.7/go.mod h1:Pe7gBlGdc8clY5LJ0LpJXMt5AmgmWNH1g+oFFVUHOEc= github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/icza/bitio v1.1.0 h1:ysX4vtldjdi3Ygai5m1cWy4oLkhWTAi+SyO6HC8L9T0= +github.com/icza/bitio v1.1.0/go.mod h1:0jGnlLAx8MKMr9VGnn/4YrvZiprkvBelsVIbA9Jjr9A= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6 h1:8UsGZ2rr2ksmEru6lToqnXgA8Mz1DP11X4zSJ159C3k= +github.com/icza/mighty v0.0.0-20180919140131-cfd07d671de6/go.mod h1:xQig96I1VNBDIWGCdTt54nHt6EeI639SmHycLYL7FkA= github.com/iskorotkov/avro/v2 v2.35.0 h1:UJoOjHeInrzB09APUZP28nJxyWeKenrPctDVx3VS3C4= github.com/iskorotkov/avro/v2 v2.35.0/go.mod h1:msR3h6CL3GwE4r6s8LgN1dUUHlm8mHx8tVvCZF8H5Xo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -951,6 +958,10 @@ github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle/v2 v2.2.3 h1:f8HoREISb3l5eO9coPgK7U3hKLhWGokOFVcThl5jrao= github.com/jackc/puddle/v2 v2.2.3/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jfreymuth/oggvorbis v1.0.5 h1:u+Ck+R0eLSRhgq8WTmffYnrVtSztJcYrl588DM4e3kQ= +github.com/jfreymuth/oggvorbis v1.0.5/go.mod h1:1U4pqWmghcoVsCJJ4fRBKv9peUJMBHixthRlBeD6uII= +github.com/jfreymuth/vorbis v1.0.2 h1:m1xH6+ZI4thH927pgKD8JOH4eaGRm18rEE9/0WKjvNE= +github.com/jfreymuth/vorbis v1.0.2/go.mod h1:DoftRo4AznKnShRl1GxiTFCseHr4zR9BN3TWXyuzrqQ= github.com/jinzhu/copier v0.3.5 h1:GlvfUwHk62RokgqVNvYsku0TATCF7bAHVwEXoBh3iJg= github.com/jinzhu/copier v0.3.5/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg= github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg= @@ -990,6 +1001,12 @@ github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/mewkiz/flac v1.0.14 h1:hyRGAM8NCKznoPmIi9zz2jyO+nfmxY2ErqBnHZ+gxh4= +github.com/mewkiz/flac v1.0.14/go.mod h1:HfPYDA+oxjyuqMu2V+cyKcxF51KM6incpw5eZXmfA6k= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d h1:IL2tii4jXLdhCeQN69HNzYYW1kl0meSG0wt5+sLwszU= +github.com/mewkiz/pkg v0.0.0-20250417130911-3f050ff8c56d/go.mod h1:SIpumAnUWSy0q9RzKD3pyH3g1t5vdawUAPcW5tQrUtI= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985 h1:h8O1byDZ1uk6RUXMhj1QJU3VXFKXHDZxr4TXRPGeBa8= +github.com/mewpkg/term v0.0.0-20241026122259-37a80af23985/go.mod h1:uiPmbdUbdt1NkGApKl7htQjZ8S7XaGUAVulJUJ9v6q4= github.com/microsoft/go-mssqldb v1.11.2 h1:FCgeBIK8um2+X4tbun6Q71N1KsfyCDPKY41e1yGVjSE= github.com/microsoft/go-mssqldb v1.11.2/go.mod h1:CYgwG5AMXFojbjTg+GNP5G/y6uz1BhTyZaPqQWzkGnQ= github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE= @@ -1315,6 +1332,7 @@ golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220712014510-0a85c31ab51e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= diff --git a/internal/app/leak_e2e_test.go b/internal/app/leak_e2e_test.go index 0279cab46b..1b61f00558 100644 --- a/internal/app/leak_e2e_test.go +++ b/internal/app/leak_e2e_test.go @@ -29,6 +29,7 @@ import ( "github.com/blackbirdworks/gopherstack/pkgs/chaos" "github.com/blackbirdworks/gopherstack/pkgs/service" cloudtrailbackend "github.com/blackbirdworks/gopherstack/services/cloudtrail" + ddbbackend "github.com/blackbirdworks/gopherstack/services/dynamodb" ) const ( @@ -61,6 +62,9 @@ type leakEnv struct { // resetBounded clears the intentionally bounded event stores (CloudTrail // keeps up to 100k events) so they do not mask real growth. resetBounded func() + // drainDeleted finalises resources queued for async deletion so the + // snapshots never straddle a janitor pass. + drainDeleted func() cfg aws.Config } @@ -101,7 +105,14 @@ func newLeakEnv(t *testing.T) *leakEnv { ct, ok := byName["CloudTrail"].(*cloudtrailbackend.Handler) require.True(t, ok) - return &leakEnv{cfg: cfg, resetBounded: ct.Reset} + ddb, ok := byName["DynamoDB"].(*ddbbackend.DynamoDBHandler) + require.True(t, ok) + + return &leakEnv{ + cfg: cfg, + resetBounded: ct.Reset, + drainDeleted: func() { ddb.DrainDeletedTables(context.Background()) }, + } } // leakOwnedSeries reports whether the series carries a label value naming a @@ -122,6 +133,7 @@ func takeLeakSnapshot(t *testing.T, env *leakEnv) leakSnapshot { t.Helper() env.resetBounded() + env.drainDeleted() for range 3 { runtime.GC() @@ -492,9 +504,8 @@ func TestLeakDynamoDB(t *testing.T) { ctx := context.Background() cases := []struct { - op func(t *testing.T, c *sdkdynamodb.Client) func(i int) - name string - settle bool + op func(t *testing.T, c *sdkdynamodb.Client) func(i int) + name string }{ {name: "item_crud", op: func(t *testing.T, c *sdkdynamodb.Client) func(int) { t.Helper() @@ -593,7 +604,7 @@ func TestLeakDynamoDB(t *testing.T) { _, err = c.DeleteTable(ctx, &sdkdynamodb.DeleteTableInput{TableName: aws.String(name)}) require.NoError(t, err) } - }, settle: true}, + }}, {name: "transact_unique_token", op: func(t *testing.T, c *sdkdynamodb.Client) func(int) { t.Helper() leakDDBTable(t, c, "leak-tok", false) @@ -673,8 +684,6 @@ func TestLeakDynamoDB(t *testing.T) { //nolint:paralleltest // measures process-wide heap and goroutine counts t.Run(tc.name, func(t *testing.T) { env := newLeakEnv(t) - budget := budget - budget.settle = tc.settle assertNoLeak(t, env, budget, tc.op(t, leakDDB(env))) }) } diff --git a/internal/app/timestreaminfluxdb_wiring_test.go b/internal/app/timestreaminfluxdb_wiring_test.go index 7d8f0e5854..7096c74d3f 100644 --- a/internal/app/timestreaminfluxdb_wiring_test.go +++ b/internal/app/timestreaminfluxdb_wiring_test.go @@ -71,9 +71,6 @@ func TestTimestreamInfluxDBAuthSecretWiring(t *testing.T) { assert.Equal(t, tt.wantUsername, secret["username"]) assert.Equal(t, "Passw0rdPassw0rd", secret["password"]) assert.Len(t, secret["token"], 64) - - _, err = ts.DeleteDbInstance(t.Context(), ×treaminfluxdb.DeleteDbInstanceInput{Identifier: out.Id}) - assert.Error(t, err, "a CREATING instance cannot be deleted yet") }) } } diff --git a/pkgs/aadauth/claims.go b/pkgs/aadauth/claims.go index 7cdb77d748..1e1d7c643d 100644 --- a/pkgs/aadauth/claims.go +++ b/pkgs/aadauth/claims.go @@ -21,7 +21,12 @@ func (iss *Issuer) Parse(tokenString string) (jwt.MapClaims, error) { return nil, fmt.Errorf("%w: unexpected signing method", ErrInvalidToken) } - return &iss.privateKey.PublicKey, nil + priv, err := iss.key() + if err != nil { + return nil, err + } + + return &priv.PublicKey, nil }) if err != nil { return nil, fmt.Errorf("%w: %w", ErrInvalidToken, err) diff --git a/pkgs/aadauth/export_test.go b/pkgs/aadauth/export_test.go new file mode 100644 index 0000000000..eba2e48490 --- /dev/null +++ b/pkgs/aadauth/export_test.go @@ -0,0 +1,4 @@ +package aadauth + +// KeyGenerated reports whether the RSA key has been generated yet. +func (iss *Issuer) KeyGenerated() bool { return iss.generated.Load() } diff --git a/pkgs/aadauth/issuer.go b/pkgs/aadauth/issuer.go index 2ec4da7560..bc819aa607 100644 --- a/pkgs/aadauth/issuer.go +++ b/pkgs/aadauth/issuer.go @@ -23,6 +23,8 @@ import ( "crypto/rsa" "encoding/base64" "fmt" + "sync" + "sync/atomic" "time" "github.com/golang-jwt/jwt/v5" @@ -52,26 +54,32 @@ const DefaultTokenExpirySeconds = 3599 // which is acceptable because validation itself is opt-in and off by default // (AZURE.md section 10.5). type Issuer struct { - privateKey *rsa.PrivateKey - keyID string + key func() (*rsa.PrivateKey, error) + keyID string + generated atomic.Bool } -// NewIssuer generates a fresh RSA-2048 keypair and a random key ID. +// NewIssuer returns an issuer with a random key ID; its RSA-2048 keypair is +// generated on first use, so unused issuers cost no key generation. func NewIssuer() (*Issuer, error) { - privateKey, err := rsa.GenerateKey(rand.Reader, rsaKeyBits) - if err != nil { - return nil, fmt.Errorf("aadauth: generating RSA key: %w", err) - } - kidBytes := make([]byte, keyIDLen) - if _, err = rand.Read(kidBytes); err != nil { + if _, err := rand.Read(kidBytes); err != nil { return nil, fmt.Errorf("aadauth: generating key ID: %w", err) } - return &Issuer{ - privateKey: privateKey, - keyID: base64.RawURLEncoding.EncodeToString(kidBytes), - }, nil + iss := &Issuer{keyID: base64.RawURLEncoding.EncodeToString(kidBytes)} + iss.key = sync.OnceValues(func() (*rsa.PrivateKey, error) { + iss.generated.Store(true) + + k, err := rsa.GenerateKey(rand.Reader, rsaKeyBits) + if err != nil { + return nil, fmt.Errorf("aadauth: generating RSA key: %w", err) + } + + return k, nil + }) + + return iss, nil } // ClientCredentialsClaims are the AAD v2.0-shaped claims this package @@ -125,10 +133,15 @@ func (iss *Issuer) IssueClientCredentialsToken(claims ClientCredentialsClaims, e jwtClaims["scp"] = claims.Scope } + priv, err := iss.key() + if err != nil { + return "", err + } + token := jwt.NewWithClaims(jwt.SigningMethodRS256, jwtClaims) token.Header["kid"] = iss.keyID - signed, err := token.SignedString(iss.privateKey) + signed, err := token.SignedString(priv) if err != nil { return "", fmt.Errorf("aadauth: signing token: %w", err) } @@ -146,5 +159,10 @@ func (iss *Issuer) PublicKeyForKID(kid string) (*rsa.PublicKey, bool) { return nil, false } - return &iss.privateKey.PublicKey, true + priv, err := iss.key() + if err != nil { + return nil, false + } + + return &priv.PublicKey, true } diff --git a/pkgs/aadauth/issuer_lazy_test.go b/pkgs/aadauth/issuer_lazy_test.go new file mode 100644 index 0000000000..9c46a23d30 --- /dev/null +++ b/pkgs/aadauth/issuer_lazy_test.go @@ -0,0 +1,43 @@ +package aadauth_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/aadauth" +) + +func TestIssuer_KeyGeneratedLazily(t *testing.T) { + t.Parallel() + + tests := []struct { + use func(iss *aadauth.Issuer) + name string + want bool + }{ + {name: "construct_only", use: func(*aadauth.Issuer) {}, want: false}, + {name: "key_id_only", use: func(iss *aadauth.Issuer) { _ = iss.KeyID() }, want: false}, + {name: "jwks", use: func(iss *aadauth.Issuer) { _ = iss.JWKS() }, want: true}, + { + name: "issue_token", + use: func(iss *aadauth.Issuer) { + _, err := iss.IssueClientCredentialsToken(aadauth.ClientCredentialsClaims{ClientID: "c"}, 0) + assert.NoError(t, err) + }, + want: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + iss, err := aadauth.NewIssuer() + require.NoError(t, err) + tt.use(iss) + assert.Equal(t, tt.want, iss.KeyGenerated()) + }) + } +} diff --git a/pkgs/aadauth/jwks.go b/pkgs/aadauth/jwks.go index 08488167b6..aaa33fd47f 100644 --- a/pkgs/aadauth/jwks.go +++ b/pkgs/aadauth/jwks.go @@ -23,7 +23,12 @@ type JWK struct { // JWKS returns the JSON Web Key Set for this issuer. func (iss *Issuer) JWKS() JWKSResponse { - pub := &iss.privateKey.PublicKey + priv, err := iss.key() + if err != nil { + return JWKSResponse{Keys: []JWK{}} + } + + pub := &priv.PublicKey n := base64.RawURLEncoding.EncodeToString(pub.N.Bytes()) eBytes := big.NewInt(int64(pub.E)).Bytes() e := base64.RawURLEncoding.EncodeToString(eBytes) diff --git a/pkgs/persistence/testdata/snapshot_inventory.json b/pkgs/persistence/testdata/snapshot_inventory.json index bbb2631486..2ed1552e28 100644 --- a/pkgs/persistence/testdata/snapshot_inventory.json +++ b/pkgs/persistence/testdata/snapshot_inventory.json @@ -3518,9 +3518,11 @@ "logicActionRec.Inputs logicContent `json:\"inputs\"`", "logicActionRec.Name string `json:\"name\"`", "logicActionRec.Outputs logicContent `json:\"outputs\"`", + "logicActionRec.Requests []*logicRequestRec `json:\"requests,omitempty\"`", "logicActionRec.Start time.Time `json:\"start\"`", "logicActionRec.Status string `json:\"status\"`", "logicActionRec.Taints bool `json:\"taints,omitempty\"`", + "logicActionRec.Traces []*logicTraceRoot `json:\"traces,omitempty\"`", "logicActionRec.Tracking string `json:\"tracking,omitempty\"`", "logicActionRec.Type string `json:\"type\"`", "logicContent.Hidden bool `json:\"hidden,omitempty\"`", @@ -3539,6 +3541,13 @@ "logicHistory.Status string `json:\"status\"`", "logicHistory.Tracking string `json:\"tracking\"`", "logicHistory.Trigger string `json:\"trigger\"`", + "logicHookRec.Callback string `json:\"callback\"`", + "logicHookRec.Fingerprint string `json:\"fingerprint\"`", + "logicHookRec.Unsub map[string]any `json:\"unsub,omitempty\"`", + "logicOperation.Created time.Time `json:\"created\"`", + "logicOperation.ID string `json:\"id\"`", + "logicOperation.Kind string `json:\"kind\"`", + "logicOperation.Run string `json:\"run\"`", "logicRepIndex.Item int `json:\"item\"`", "logicRepIndex.Scope string `json:\"scope\"`", "logicRepRec.Action string `json:\"action\"`", @@ -3546,6 +3555,18 @@ "logicRepRec.Name string `json:\"name\"`", "logicRepRec.Rec logicActionRec `json:\"rec\"`", "logicRepRec.Scope bool `json:\"scope,omitempty\"`", + "logicRequestRec.Body any `json:\"body,omitempty\"`", + "logicRequestRec.BodySize int64 `json:\"bodySize,omitempty\"`", + "logicRequestRec.End time.Time `json:\"end\"`", + "logicRequestRec.HasBody bool `json:\"hasBody,omitempty\"`", + "logicRequestRec.Method string `json:\"method\"`", + "logicRequestRec.Name string `json:\"name\"`", + "logicRequestRec.ReqHeaders map[string]string `json:\"reqHeaders,omitempty\"`", + "logicRequestRec.RespHeaders map[string]string `json:\"respHeaders,omitempty\"`", + "logicRequestRec.Responded bool `json:\"responded,omitempty\"`", + "logicRequestRec.Start time.Time `json:\"start\"`", + "logicRequestRec.Status int `json:\"status,omitempty\"`", + "logicRequestRec.URI string `json:\"uri\"`", "logicRunRec.Actions map[string]*logicActionRec `json:\"actions\"`", "logicRunRec.ClientID string `json:\"clientTrackingId,omitempty\"`", "logicRunRec.Code string `json:\"code,omitempty\"`", @@ -3570,11 +3591,21 @@ "logicRunTrigger.Status string `json:\"status\"`", "logicRunTrigger.Tracking string `json:\"tracking,omitempty\"`", "logicSnapshot.Workflows map[string]*logicWorkflow `json:\"workflows,omitempty\"`", + "logicTraceNode.Err string `json:\"err,omitempty\"`", + "logicTraceNode.HasValue bool `json:\"hasValue,omitempty\"`", + "logicTraceNode.Subs []*logicTraceNode `json:\"subs,omitempty\"`", + "logicTraceNode.Text string `json:\"text\"`", + "logicTraceNode.Value any `json:\"value,omitempty\"`", + "logicTraceRoot.Node logicTraceNode `json:\"node\"`", + "logicTraceRoot.Path string `json:\"path\"`", "logicTriggerState.Anchor time.Time `json:\"anchor\"`", "logicTriggerState.Changed time.Time `json:\"changed\"`", "logicTriggerState.Created time.Time `json:\"created\"`", + "logicTriggerState.Hook *logicHookRec `json:\"hook,omitempty\"`", + "logicTriggerState.HookPending bool `json:\"-\"`", "logicTriggerState.Last *time.Time `json:\"last,omitempty\"`", "logicTriggerState.Next *time.Time `json:\"next,omitempty\"`", + "logicTriggerState.PollURL string `json:\"pollUrl,omitempty\"`", "logicTriggerState.State string `json:\"state\"`", "logicVersion.Created time.Time `json:\"created\"`", "logicVersion.Definition map[string]any `json:\"definition\"`", @@ -3590,6 +3621,7 @@ "logicWorkflow.KeySecondary string `json:\"keySecondary\"`", "logicWorkflow.Location string `json:\"location\"`", "logicWorkflow.Name string `json:\"name\"`", + "logicWorkflow.Operations []*logicOperation `json:\"operations,omitempty\"`", "logicWorkflow.Parameters map[string]any `json:\"parameters,omitempty\"`", "logicWorkflow.ResourceGrp string `json:\"resourceGroup\"`", "logicWorkflow.Runs []*logicRunRec `json:\"runs\"`", diff --git a/services/azurearm/PARITY.md b/services/azurearm/PARITY.md index f8477f0912..164b75aeea 100644 --- a/services/azurearm/PARITY.md +++ b/services/azurearm/PARITY.md @@ -93,18 +93,18 @@ items_still_open: - "Compute: disks accept Empty, FromImage, Copy, CopyStart and Upload; Import and ImportSecure (the blob in storageAccountId is not read: no seam from services/azurearm to services/azureblob), Restore (needs Azure Backup recovery points; Microsoft.RecoveryServices is not modelled), UploadPreparedSecure, CopyFromSanSnapshot and Attach are rejected, beginGetAccess/endGetAccess answer 501 (no disk bytes exist behind an SAS URL; an Upload disk stays ReadyToUpload), and Ultra/Premium v2 IOPS limits, shared disks (maxShares), bursting, encryption sets and zone-versus-VM zone matching are stored but not enforced." - "Compute: Uniform scale set instances do not get the public IP addresses of publicIPAddressConfiguration (accepted, not realised); autoscale (Microsoft.Insights/autoscalesettings stays in the generic store, and no metric feeds rules); rolling upgrades complete synchronously, so batch sizing, pauseTimeBetweenBatches, health gating and maxSurge are recorded in the policy but not run; the instance-level update changes tags, protectionPolicy, licenseType, userData, diagnosticsProfile and additionalCapabilities, and other changed properties are refused." - "ManagedIdentity: assignmentRestrictions and the api-versions 2025-01-31-preview and 2025-05-31-preview are not implemented; isolationScope is stored and echoed but never enforced; listAssociatedResources scans Compute, Web, Container Instances, Container Apps and AKS resources only; resource group deletion removes same-named groups of identities in every subscription." - - "API Management: not modelled - the built-in all-access (master) subscription, the starter/unlimited products and built-in groups, diagnostics, certificates, gateways (self-hosted), portal, schemas, API revisions/releases, user subscriptions, wikis, issues, tenant settings, backup/restore, soft-delete/restore, custom hostnames, virtual networks, multi-region, private endpoints, v2 tiers (BasicV2, StandardV2) and the Isolated sku; they fall to 404 or are rejected. $top, $skip, count and nextLink paging work on the child lists; $filter is honoured on the APIs, API operations, product API, products, backends, named values (displayName only), tags, authorization servers, OpenID Connect providers, groups, users, subscriptions, loggers and policy fragment lists, and ignored on the other lists (the SDK documents no $filter for them)." - - "API Management gateway: policies outside the subset (validate-jwt, quota, cache, choose, set-variable, send-request, authentication-*, policy expressions, product-scope policies, on-error execution, rate-limit nested api/operation, forward-request http-version/continue-timeout/buffer-*/fail-on-error-status-code, cors terminate-unmatched-request) are refused at PUT or not honoured; the backend section runs set-header/set-query-parameter/set-backend-service/forward-request in order and a chain with no forward-request answers an empty 200. The cors policy page gives two defaults for terminate-unmatched-request (false in the attribute table, true in the usage notes), so unmatched simple requests proceed without CORS headers. set-header on Connection, Content-Length, Keep-Alive and Transfer-Encoding is accepted but those headers are never forwarded (Learn: they cannot be changed)." - - "API Management gateway: WebSocket and GraphQL APIs are served as plain HTTP passthrough (ws/wss serviceUrl answers 500); HTTP (non-TLS) calls are impossible because the ARM listener is HTTPS, so an API whose protocols exclude https answers 404; the gateway has no client-certificate, IP or JWT checks; failed upstream calls answer 502 where the real gateway answers 500 (unverified); the unknown-host 404 body Resource not found and the 503 body of a service that is still activating are gopherstack wording, not documented." + - "API Management: not modelled - gateways (self-hosted), portal, user subscriptions, wikis, issues, tenant settings, backup/restore, soft-delete/restore, custom hostnames, virtual networks, multi-region, private endpoints, v2 tiers (BasicV2, StandardV2) and the Isolated sku; they fall to 404 or are rejected. $top, $skip, count and nextLink paging work on the child lists; $filter is honoured on the APIs, API operations, product API, products, backends, named values (displayName only), tags, authorization servers, OpenID Connect providers, groups, users, subscriptions, loggers and policy fragment lists, and ignored on the other lists (the SDK documents no $filter for them)." + - "API Management gateway: policies outside the subset (authentication-managed-identity, policy expressions beyond the documented subset, on-error for built-in pipeline errors such as a missing subscription key or an unmatched operation, rate-limit nested api/operation, forward-request http-version/continue-timeout/buffer-*/fail-on-error-status-code, cors terminate-unmatched-request) are refused at PUT or not honoured; the backend section runs set-header/set-query-parameter/set-backend-service/forward-request in order and a chain with no forward-request answers an empty 200. The cors policy page gives two defaults for terminate-unmatched-request (false in the attribute table, true in the usage notes), so unmatched simple requests proceed without CORS headers. set-header on Connection, Content-Length, Keep-Alive and Transfer-Encoding is accepted but those headers are never forwarded (Learn: they cannot be changed)." + - "API Management gateway: HTTP (non-TLS) calls are impossible because the ARM listener is HTTPS, so an API whose protocols exclude https answers 404; the gateway has no client-certificate checks (validate-client-certificate, context.Request.Certificate); failed upstream calls answer 502 where the real gateway answers 500 (unverified); the unknown-host 404 body Resource not found and the 503 body of a service that is still activating are gopherstack wording, not documented." - "Authorization: with --azure-arm-enforce-rbac, ARM requests under a resource group are evaluated against the bearer token's role assignments (action derived as {namespace}/{type}/{read|write|delete|action}); data planes, subscription-level and management-group requests are not evaluated; there is no deny-assignment API because only Blueprints, managed applications and similar services create deny assignments and none is emulated, so evaluation has no deny source; no PIM/eligibility/schedule, classic administrator or provider-operations API, no management-group scope for locks, and management group scopes are accepted but never checked to exist; managed-identity token endpoints do not exist, so a system-assigned identity cannot obtain a token to be evaluated." - "Authorization: ScopeLocked enforcement covers the ARM listener only (not data planes, as documented); it does not model the documented exceptions where services act on locked resources, resource moves, or Microsoft.Authorization extension resources other than the lock itself inheriting a lock (role assignments and policy assignments do inherit it)." - "Authorization: role assignment conditions (ABAC) are stored and validated (conditionVersion 2.0, balanced brackets) but never evaluated, because evaluation needs the request attributes of the data plane that carries the attribute namespaces; delegatedManagedIdentityResourceId is stored; the last-owner deletion guard does not exist; assignableScopes of management groups are not checked to exist; list calls are not paged (no nextLink/$skipToken)." - "Policy: deny, audit, append and modify are evaluated at write time (PUT of a resource group or resource) for rules that read type, name, id, location, kind and tags with parameters(), concat() and field(); rules that read aliases, requestContext() or resourceGroup() are skipped, as are auditIfNotExists, deployIfNotExists and denyAction, so no remediation, policy versions, tokens or allowed-locations deny on aliased types exist; compliance states are recorded per resource and definition and persisted, but there is no Microsoft.PolicyInsights read API because armpolicyinsights is not in the module cache; exemptions are honoured; policyDefinitions is limited to a 13-definition and 1-initiative built-in catalog; initiative parameters are not checked against their member definitions; the Guest Configuration provider does not exist." - "Authorization: management-group scoped policy assignments have no Terraform fixture (azurerm_management_group needs a tenant-level group API the emulator does not model); azurerm_role_definition, subscription policy assignments and policy set definitions are applied, planned clean and destroyed by TestTerraform_Azure_AuthorizationScoped, and test/terraform/azure/flexible_test.go and apim_test.go cover the Flexible Server and API Management resources named there." - - "Logic: not routed (answer 404 NotFound): workflows move, generateUpgradedDefinition and listSwagger, run operations, requestHistories and listExpressionTraces, and every Integration Account and Integration Service Environment API." - - "Logic: only Request and Recurrence triggers fire. Http polling, HttpWebhook, Workflow and SlidingWindow triggers are stored but never run." - - "Logic expression functions: date formatting and parsing know the en-US, fr-FR and es-ES names only; other locales are rejected." - - "Logic: the Http action authenticates with Basic, Raw and ActiveDirectoryOAuth (Secret credential) only; ActiveDirectoryOAuth with the Certificate credential, ClientCertificate (no PFX client-certificate transport) and ManagedServiceIdentity (the emulator has no managed-identity token endpoint) are rejected." + - "Logic: not routed (answer 404 NotFound): workflows move and generateUpgradedDefinition, and every Integration Account and Integration Service Environment API." + - "Logic: only Request, Recurrence, Http polling and HttpWebhook triggers fire. SlidingWindow triggers are stored but never run (the Learn trigger reference has no section on it)." + - "Logic expression functions: date formatting and parsing know 19 cultures (en-US, en-GB, fr-FR, es-ES, de-DE, it-IT, pt-BR, pt-PT, nl-NL, sv-SE, da-DK, nb-NO, fi-FI, pl-PL, ja-JP, zh-CN, ko-KR, ru-RU, tr-TR); other locales are rejected." + - "Logic: the Http action authenticates with Basic, Raw, ClientCertificate and ActiveDirectoryOAuth (Secret and Certificate credentials); ManagedServiceIdentity is rejected (the emulator has no managed-identity token endpoint the Logic provider can reuse)." leaks: {status: clean, note: "Handler.StartWorker's listener goroutine is the only background goroutine this service starts; covered by leak_test.go's TestMain (pkgs/testleak) plus TestHandler_StartWorker_BindsServesHTTPS/TestHandler_StartWorker_BindFailureIsSynchronous exercising bind/serve/shutdown."} --- @@ -221,11 +221,16 @@ Sources: Learn REST reference for Compute ssh-public-keys generate-key-pair (307 - Authorization (unverified, recalled only - no primary source found): the error codes InvalidRoleAssignmentId (non-GUID name), RoleAssignmentNotFound (GET of a missing assignment), RoleDefinitionDoesNotExist for GET (the text is documented, the 404 status is not), RoleAssignmentScopeNotAssignableToRoleDefinition, RoleDefinitionWithSameNameExists, RoleAssignmentExists and its text, LockNotFound, InvalidLockName, PolicyDefinitionNotFound, PolicySetDefinitionNotFound, PolicyAssignmentNotFound, InvalidPolicyRule, InvalidFilter, InvalidScope, MissingPolicyParameter, PolicyDefinitionInUse and PolicySetDefinitionInUse; the ScopeLocked text for a POST ('action') and the listing of several locked scopes; DELETE of a missing role assignment/lock/policy answering 204; assignedTo() semantics (modelled as at-or-above); the unfiltered list defaults (at and below). - Logic Recurrence: timeZone takes Windows names (CLDR windowsZones.xml, punctuation optional) or IANA names and, per learn.microsoft.com/azure/logic-apps/logic-apps-workflow-actions-triggers, startTime without a zone offset is read in that zone; schedule hours, minutes, weekDays and monthDays are evaluated in the zone and keep their wall-clock time across daylight saving changes. The page says timeZone applies only with a startTime; without one the emulator still evaluates the schedule in the zone. schedule.monthlyOccurrences and monthDays are not in the workflow definition reference, so monthlyOccurrences is not modelled. - Logic trigger conditions: each conditions[].expression must evaluate to a boolean (the Learn page does not say what a non-boolean does); when one is false no run starts and the trigger history records a Skipped entry with fired false, an evaluation error records Failed with code TriggerConditionError (both statuses and codes are the emulator's choice, the page does not say what a false condition records), and a Request trigger answers 202 Accepted to the caller. The page's example uses triggers().code, which the emulator does not define; use triggerBody(), triggerOutputs() and trigger(). -- Logic expression functions, unverified or limited: date formatting and parsing know the en-US, fr-FR and es-ES names only; nthIndexOf ignores case like indexOf (the reference is silent); xml() writes object properties in sorted key order (JSON objects are unordered in this engine, the reference examples keep definition order); xpath returns an element as serialized XML and rejects namespace prefixes in name tests (.NET XPath needs a namespace manager; use name(), local-name(), namespace-uri()) and the Learn examples print element results as bare text; listCallbackUrl() always fails because it is valid only in HttpWebhook and ApiConnectionWebhook triggers and actions, which never run; formData and multipart functions read $content/$content-type bodies, $formdata and $multipart arrays and plain urlencoded or multipart string bodies, a shape inferred from the request trigger. +- Logic expression functions, unverified or limited: date formatting and parsing use the culture table in rp_logic_locales.go (generated from the CLDR gregorian data in golang.org/x/text v0.44.0: month and day names, abbreviations, AM/PM designators, short/full date and short/medium time patterns converted to .NET syntax; the .NET culture data on Windows can differ, so the standard specifiers d, D, f, F, g, G, t, T are an emulator choice per culture, f/F/g/G join date and time with one space, M and Y stay "MMMM d" and "MMMM yyyy" with localized names because the CLDR tree used has no availableFormats, R/r, s, o, u are culture-invariant); nthIndexOf ignores case like indexOf (the reference is silent); xml() writes object properties in sorted key order (JSON objects are unordered in this engine, the reference examples keep definition order); xpath returns an element as serialized XML and rejects namespace prefixes in name tests (.NET XPath needs a namespace manager; use name(), local-name(), namespace-uri()) and the Learn examples print element results as bare text; listCallbackUrl() returns the trigger callback URL while an HttpWebhook subscribe or unsubscribe call is evaluated and fails anywhere else (ApiConnectionWebhook and HttpWebhook actions never run); formData and multipart functions read $content/$content-type bodies, $formdata and $multipart arrays and plain urlencoded or multipart string bodies, a shape inferred from the request trigger. - Logic (recalled service behaviour, unverified): the callback URL host/path layout and the HMAC signature scheme (the service does not document it), error codes and statuses for a missing or wrong signature (DirectApiAuthorizationRequired, AuthorizationFailed), WorkflowDisabled, TriggerRequestMethodNotValid, InvalidTriggerType, RunNotRunning and the TriggerInputSchemaMismatch message text, 202 when a run finishes without sending its Response, the unhandled-failure rule that decides run and scope status, Until reporting TimedOut at its limit, Foreach default concurrency 20, the default Http retry policy (exponential, 4 attempts, PT7S), True/False string rendering of booleans, run and version identifier formats, x-ms-workflow-* request and response headers, and the 100 MB request body bound. - RBAC enforcement (--azure-arm-enforce-rbac, --azure-arm-rbac-superusers): off by default; a request without a valid bearer token answers 401, a denied one 403 AuthorizationFailed with the message recalled from the service (not published); the superuser list exists only so a first role assignment can be made. permissions at resource group and resource scope lists one entry per distinct role the caller holds at or above the scope. - Policy at write time: a deny answers 403 RequestDisallowedByPolicy (the code is documented in Learn troubleshooting, the message text is recalled); string comparisons are case-insensitive; a tag name match is case-insensitive; an unevaluable rule leaves no state; compliance state keeps the latest result per resource, assignment and definition (bounded to 5000). - Compute: Spot validation (priority Regular, Low or Spot; evictionPolicy Deallocate or Delete and billingProfile only with Spot or Low; maxPrice -1 or above zero) and its 400 messages are not published verbatim; simulateEviction evicts at once (the service evicts within 30 minutes) by deallocating or deleting per evictionPolicy; reapply and reimage record the platform operation (reimage restarts a running machine and is refused when deallocated) and change only the etag and power state; attachDetachDataDisks refuses a disk that is attached or not attached with 400 and OperationNotAllowed messages that are not published. +- Logic run history surface: requestHistories exist in armlogic v1.2.0 only for run actions and action repetitions (WorkflowRunActionRequestHistories, WorkflowRunActionRepetitionsRequestHistories); there is no trigger requestHistories client, so none is routed. One record is kept per outbound call the engine made for an Http action (each attempt, retry and 202 poll; at most 100 per action). Credential headers (Authorization, Proxy-Authorization, Cookie, Set-Cookie) are omitted rather than masked, the service's masking form is not documented. Response bodies up to 256 KiB are stored and served through a signed bodyLink; larger ones record contentSize only. With secure inputs the uri and request headers are omitted, with secure outputs the response headers and bodyLink are. listExpressionTraces (action and repetition) returns the template strings evaluated in the action's inputs with the evaluated value and the evaluated sub-expressions (path inputs., text is the source string); the wire shape is armlogic ExpressionTraces/ExpressionRoot, the trace content is an emulator choice (bounded to 100 roots per action, 200 nodes, depth 8, values over 16 KiB omitted; secure inputs omit values; values are also omitted under inputs.authentication, inputs.cookie and the Authorization, Proxy-Authorization and Cookie headers, and for any expression reading a secureString or secureObject parameter by parameters('name'), a variable set from one is not tracked). One run keeps at most 2000 request records, 4 MiB of stored response bodies (later calls keep contentSize only) and 1000 expression trace roots, so a loop of thousands of iterations cannot grow the run without bound; the limits are an emulator choice. The repetitions lists are unpaged (the armlogic repetitions pager has no nextLink), so they return every iteration. Run operations: GET runs/{r}/operations/{id} answers the run; ids are minted by resubmit and cancel (returned in the Location header, an emulator choice) and an id that belongs to another run answers 404. +- Logic Http trigger: polls on its recurrence through the loopback-gated client (no widening of the Http action outbound rule), 200 starts a run with outputs statusCode/headers/body and inputs, any other status records a Skipped history entry, a Location header becomes the next poll URL (a Location on another origin is polled with a bare GET carrying only the x-ms-workflow-* headers and no client certificate; the dial is still loopback-gated), Retry-After as delay-seconds or an HTTP-date delays the next poll when later than the recurrence and is clamped to 24 hours (the clamp is an emulator choice) (Learn: logic-apps-workflow-actions-triggers, HTTP trigger). A transport failure records a Failed history entry with code TriggerRequestFailed (or TriggerTimedOut), codes the page does not give. Run on the trigger polls once. No async 202 polling is done for the trigger. +- Logic trigger types: the Learn trigger reference lists HTTP, HTTPWebhook, Recurrence, Request, ApiConnection and ApiConnectionWebhook ("Workflow" appears only as an action type), so a Workflow trigger is not modelled. SlidingWindow is accepted by the definition validator but the page has no section on it, so delay, windowStartTime/windowEndTime and catch-up are not implemented. +- Logic HttpWebhook trigger (Learn: logic-apps-workflow-actions-triggers, "Webhooks and subscriptions"): the subscribe call is sent when the workflow and trigger are enabled (create, update, enable) and the unsubscribe when the trigger is disabled or removed, the workflow is disabled or deleted, or the subscribe call changes; a changed subscribe call unsubscribes the old one first. Calls are queued and sent by one background worker outside the backend lock through the Http action outbound rules (loopback-gated, retry policy, authentication), so they complete shortly after the ARM call answers, an emulator choice. A 2xx-3xx answer is success (the page defines no success status); a failed subscribe records a Failed trigger history entry (code TriggerRequestFailed, not on the page) and is retried on the next enable or update. @{listCallbackUrl()} is the signed callback URL of the trigger built from the Host of the latest ARM write (PUT, PATCH, POST) to that workflow, kept per workflow, the same Host-derived mechanism the Request trigger listCallbackUrl uses (the Logic provider has no advertised-host setting); a Host that is not a plain DNS name or IP literal with an optional valid port (userinfo, path, other characters) is ignored and the workflow keeps its earlier base, else https://localhost:{port}; a POST to it starts a run with headers and body as trigger outputs. The unsubscribe call is remembered in persisted state so it still goes out after a restart or when the trigger is deleted. A subscribe that finishes after its workflow was deleted or reset is unsubscribed at once; Reset drops queued calls. +- Logic listSwagger: Swagger 2.0 document of the workflow's Request triggers (one operation per trigger on /triggers/{name}/paths/invoke[/relativePath], method default POST, path parameters from {braces} in relativePath, the api-version, sp, sv and sig query parameters, the JSON schema as the body parameter for methods with a body). The document layout is an emulator choice, the service does not document it. generateUpgradedDefinition and workflows move stay unrouted: the schema upgrade transformation is not documented and the package has no cross-group move mechanism. - Logic resubmit: POST triggers/{t}/histories/{h}/resubmit starts a new run from the recorded trigger inputs and outputs and answers 202; a history entry that did not fire answers 400. - Flexible server backups: the first automatic backup is taken at server creation (Learn: postgresql and mysql backup concepts) and named backup_; backups outside the retention window are not listed; MySQL on-demand backups (backups PUT) carry source Full and the name pattern [A-Za-z0-9_-]{1,128} (not published); a duplicate answers 409 Conflict; backupsV2 is a read view of the same records; updateConfigurations applies all parameters or none and answers 200 with the changed parameters. - API Management plain collections (tags, groups, loggers, caches, identityProviders, authorizationServers, openidConnectProviders, apiVersionSets, policyFragments, users): validated against armapimanagement v2.1.0 enums and required fields; secrets (clientSecret, password) are accepted and never returned, logger credential values are returned as {{Logger-Credentials--}} placeholders, policy fragments must be well-formed XML with a fragment root, and group type system cannot be created. Relationships between them (group membership, user subscriptions) are not modelled. @@ -241,6 +246,7 @@ Sources: Learn REST reference for Compute ssh-public-keys generate-key-pair (307 - Logic secureData: Secure Inputs/Outputs follow learn.microsoft.com/azure/logic-apps/logic-apps-securing-a-logic-app ("Secure data in run history by using obfuscation"): the run, action, repetition and trigger-history reads omit inputsLink/outputsLink and the content URL answers 404; Compose, Parse JSON and Response hide outputs together with inputs; the documented unsupported types ignore the setting; an action whose inputs name (outputs/body/actions) an action with secured data has its inputs hidden (outputs too for Compose, Parse JSON, Response), found by scanning the inputs for those function calls, so a reference built dynamically is not detected. Expressions still read the real values. - Logic staticResult: an Enabled runtimeConfiguration.staticResult on an Http or connector action returns the staticResults entry (status Succeeded/Failed/TimedOut/Cancelled, outputs, code, error or outputs.errors[0]) instead of running the action (learn.microsoft.com/azure/logic-apps/test-logic-apps-mock-data-static-results, logic-apps-workflow-definition-language "Static results"); the page does not give the Failed error shape, so error/code are read as written; no inputs are recorded for a mocked action. - Logic Http action: a 202 with a Location header is polled (GET, same headers minus Content-*, credentials dropped across hosts) every Retry-After seconds, default one second, until a non-202 answers, unless operationOptions has DisableAsyncPattern (learn.microsoft.com/azure/logic-apps/logic-apps-create-api-app, azure/connectors/connectors-native-http); polling stops at the action timeout. The cookie input becomes the Cookie header and the headers the Learn page lists as omitted are dropped. ActiveDirectoryOAuth (Secret) POSTs grant_type=client_credentials, client_id, client_secret and resource to {authority}/{tenant}/oauth2/token (the v1 endpoint, recalled, not on the Learn page) through the loopback-gated client; the default authority is login.microsoftonline.com, so it is refused unless external hosts are allowed. +- Logic Http authentication (Learn: set-up-security-permissions): ClientCertificate takes pfx (base64 PFX) and password and presents the certificate in a TLS 1.2+ handshake on a per-request transport with the same loopback-gated dialer; the server is verified against the system roots (tests inject a pool with SetOutboundRootCAs), never InsecureSkipVerify. An undecodable PFX or wrong password fails the action with code BadRequest and "Could not load private key" (the text the page quotes for that error; the code mapping is recalled). ActiveDirectoryOAuth with credentialType Certificate sends the same form as the Secret flow with client_assertion_type jwt-bearer and a client_assertion JWT (RS256; iss and sub the client id, aud the token endpoint URL, 10 minute lifetime, x5t and x5t#S256 headers), which azuregraph AuthenticateAssertion can verify against an application key credential (the Logic tests drive a fake authority; the azuregraph HTTP token route and its v1 path were not exercised); the claim layout follows the Entra certificate-credentials convention (recalled, the Learn page lists no claims). Only RSA keys sign. The pfx, password and any value under inputs.authentication are never in action inputs, request histories or expression traces (trace values under that path, under the Authorization, Proxy-Authorization and Cookie headers and for secure parameters are dropped), and never logged. Secured parameters used for pfx and password are read like any other parameter. - Container Instances exec and attach: webSocketUri points at the ARM listener (/_aci/exec/{token}); armcontainerinstance ContainerExecResponse leaves the host unspecified. Attach streams the container output live until the container exits or the client closes the socket. - Container Instances securityContext: privileged true is rejected with 400 InvalidRequestContent (the runtime would grant host-root access); runAsGroup without runAsUser runs as user 0; seccompProfile (base64 JSON, armcontainerinstance SecurityContextDefinition) is handed to the container runtime as the profile document; capabilities lose a CAP_ prefix before they reach the runtime. - Container Instances group address: on Linux a group with ipAddress gets its own address in 127.0.0.0/8 (derived from the group key, unique within the engine) and publishes the declared TCP and UDP port numbers on it; on other hosts, and for Container Apps replicas, the address is 127.0.0.1 and ports are pool-assigned. Learn (container-instances-faq) says group addresses change and must not be depended on. @@ -265,4 +271,8 @@ Sources: Learn REST reference for Compute ssh-public-keys generate-key-pair (307 - Flexible servers, PostgreSQL SKU catalog: E6ds_v4 and confidential-compute (Standard_*C*ads_v5) SKUs are in no row of the current Learn compute table, so they are not offered; MySQL storage IOPS pre-provisioning below the SKU maximum and the B1s IOPS limit are published nowhere. - Container Apps probes: initialDelaySeconds 1-60, periodSeconds and timeoutSeconds 1-240, thresholds 1-10 with successThreshold 1 for liveness and startup come from the armappcontainers ContainerAppProbe model; a startup probe is not mapped because the Container Instances engine has no startup probe. - API Management $filter fields per list follow the tables in the armapimanagement v2.1.0 list options; operators outside a field's documented set (state, externalId and loggerType take eq only, registrationDate no functions) are refused with 400. +- API Management policy expressions: `@(...)` single expressions are parsed by a bounded recursive-descent parser (4096 characters, depth 32, 512 nodes, string results 1 MiB) and refused at PUT with a ValidationError when they use anything outside the subset; `@{...}` is refused. Subset: string, int, bool and null literals; `==` `!=` `<` `>` `<=` `>=` `&&` `||` `!` unary minus `+` `-` `*` `/` `%` `??` the ternary, `?.`, indexers and the casts (string) (int) (long) (bool) (IResponse) (Jwt); context.Request.{Method, Url, OriginalUrl, Headers, MatchedParameters, IpAddress} with Url.{Path, Query, Host, Port, Scheme, QueryString}, context.Response.{StatusCode, StatusReason, Headers}, context.Variables, context.Subscription.{Id, Name}, context.Product.{Id, Name}, context.Api.{Id, Name, Path}, context.Operation.{Id, Name, Method, UrlTemplate}, context.User.Id, context.LastError.*, context.RequestId and context.Timestamp; the methods Contains StartsWith EndsWith ToLower ToUpper Trim Equals (optionally with StringComparison.Ordinal or OrdinalIgnoreCase) ToString GetValueOrDefault (headers, query, variables, the generic form with one or two arguments) ContainsKey int.Parse string.IsNullOrEmpty Guid.NewGuid DateTime.UtcNow DateTime.Parse and DateTime.AddSeconds/Minutes/Hours/Days, Body.As() on a send-request response, Jwt.{Claims, Issuer, Subject, Algorithm, Id}. DateTime.ToString accepts o, O, s and yyyy-MM-ddTHH:mm:ssZ only; the default format is MM/dd/yyyy h:mm:ss tt (emulator choice, culture-dependent in Azure). An expression is a whole attribute or text value; `@(` inside a longer value is literal text. Unescaped quotes, ampersands and less-than signs inside an expression are accepted in the policy XML, as in the Learn examples, and stored as written. context.Subscription.Id is the subscription entity name and context.User.Id the last segment of the subscription ownerId (emulator choices; Learn gives only the types). A runtime expression failure raises ExpressionValueEvaluationFailure (500). +- API Management gateway policies: choose/when/otherwise, set-variable (typed values; 256 variables, 1 MiB each), include-fragment (one level, resolved per request from the stored fragments; a fragment is a `` of supported statements without base or nested includes), validate-jwt (Learn: validate-jwt-policy; HS256/384/512 with base64 keys, RS/PS 256/384/512 with n/e, certificate-id or an openid-config URL whose JWKS is fetched through the gateway client and cached for 1 hour with a kid-miss refresh at most every 5 minutes, 256 entries, a failed fetch remembered for 5 minutes (emulator choice); alg none is refused unless require-signed-tokens is false; an HS* token never verifies against an RSA key; decryption-keys, ES* and require-scheme on a custom header are not supported/ignored as documented; Authorization values without require-scheme use the part after the first space; validate-connectivity is accepted and never probed; failures answer failed-validation-httpcode (default 401) with the Reason values of the error-handling page and the message JSON of the other policy errors), rate-limit-by-key (sliding window, increment-condition/increment-count expressions postpone counting to the end of the pipeline), quota (product scope, per subscription, windows from the subscription start date, nested api/operation counters) and quota-by-key (fixed windows from first-period-start, one increment per key per request, minimum period 300 s), answering 403 QuotaExceeded; call counters are checked and charged in one critical section before the backend runs, so concurrent requests cannot exceed the limit, except when increment-condition or increment-count is an expression (then counted after the response, as rate-limit-by-key does) and for the bandwidth counter, which is charged after the response (emulator choices) with Retry-After; the quota message "Out of call volume quota. Quota will be replenished in hh:mm:ss." and the bandwidth variant come from the Learn error table, an infinite period omits the replenish clause and Retry-After (emulator choice), bandwidth counts request plus response bytes (emulator choice); cache-lookup/cache-store (GET only, key = host, path and the vary-by values, query strings excluded unless vary-by-query-parameter names them, 10000 entries and 64 MiB per instance, 1 MiB per entry, built-in cache only: every caching-type uses it, a hit skips the backend and still runs outbound without cache-store, downstream-caching-type adds a Cache-Control of the stated type, max-age and must-revalidate as an emulator choice) stored responses drop Set-Cookie and the hop-by-hop headers because the cache-store page is silent (emulator choice); and cache-lookup-value/cache-store-value/cache-remove-value; send-request and send-one-way-request (mode new or copy, response-variable-name, timeout up to 300 s, ignore-error, set-url/set-method/set-header/set-body; the gateway client and its loopback-only dial policy; one-way requests run detached with at most 64 in flight); authentication-basic; authentication-certificate (thumbprint, certificate-id or body+password, presenting the PFX private key to an https backend, trust anchors from SetBackendRootCAs); on-error sections with context.LastError for policy, forward and send errors (set-header, set-variable, choose, return-response, mock-response, send requests and cache values are executed there); policy id attributes feed LastError.PolicyId; the policy chain is global, product (the product of the subscription scope, or the first open product containing the API when no key is used), API and operation, each with base. +- API Management entities: service creation seeds the system groups administrators, developers and guests (descriptions as the service returns them), the all-access master subscription (scope /, active, keys generated) and, except on Consumption, the published Starter (subscriptionsLimit 1, rate-limit 5/60 s and quota 100/week as its product policy) and Unlimited (approval required) products linked to administrators and developers; the product and group contents are reproduced from the service's documented defaults without a fetched primary source and are emulator choices, and the master subscription and system groups cannot be deleted; a service restored from a snapshot that lacks the system groups or the master subscription gets them added (keys generated), existing entities of those names are kept, and the Starter and Unlimited products are not re-created because a user may have deleted them (emulator choice). Certificates take a PFX (with its password) or an X.509 DER/PEM certificate, compute subject, SHA-1 thumbprint and expirationDate from it, and never return data or password; Key Vault certificates are refused. Diagnostics (service and API scope, any identifier) require an existing logger and validate sampling, verbosity, correlation and body byte limits. Global schemas (json or xml) and API schemas (any media type, XML and JSON documents checked) are validated and stored. Revisions are APIs named `{id};rev=N` sharing the base path, listed by apis/{id}/revisions; only the current revision serves traffic and a release (apis/{id}/releases/{rid}, notes up to 500 characters) makes the referenced revision current (a release is not undone by deleting it; emulator choice). +- API Management WebSocket APIs: an upgrade request for an API whose protocols include ws or wss (wss on the HTTPS listener) runs the inbound policies of the onHandshake operation, then the gateway dials the ws/wss serviceUrl (as http/https through the gateway client) and copies frames both ways until either side closes, with at most 256 open sessions and a one-hour lifetime, forwarding the client headers without the hop-by-hop ones and applying set-backend-service credentials, authentication-basic and authentication-certificate to the handshake; Reset and Close (called by Handler.Shutdown) cancel every open session on both legs and every in-flight one-way request and wait for them; outbound policies do not run after a successful upgrade and a plain HTTP request to a WebSocket API answers 500. GraphQL APIs are plain HTTP passthrough to the serviceUrl with the schema stored as an API schema; the emulator does not synthesize resolvers. - API Management ip-filter: the page documents no response for a blocked caller, so the gateway answers 403 with a JSON body; the caller IP is the TCP peer address (no X-Forwarded-For), and addresses and ranges are literals (policy expressions are refused). diff --git a/services/azurearm/README.md b/services/azurearm/README.md index f3e1c79ae6..030858de98 100644 --- a/services/azurearm/README.md +++ b/services/azurearm/README.md @@ -45,18 +45,18 @@ - Compute: disks accept Empty, FromImage, Copy, CopyStart and Upload; Import and ImportSecure (the blob in storageAccountId is not read: no seam from services/azurearm to services/azureblob), Restore (needs Azure Backup recovery points; Microsoft.RecoveryServices is not modelled), UploadPreparedSecure, CopyFromSanSnapshot and Attach are rejected, beginGetAccess/endGetAccess answer 501 (no disk bytes exist behind an SAS URL; an Upload disk stays ReadyToUpload), and Ultra/Premium v2 IOPS limits, shared disks (maxShares), bursting, encryption sets and zone-versus-VM zone matching are stored but not enforced. - Compute: Uniform scale set instances do not get the public IP addresses of publicIPAddressConfiguration (accepted, not realised); autoscale (Microsoft.Insights/autoscalesettings stays in the generic store, and no metric feeds rules); rolling upgrades complete synchronously, so batch sizing, pauseTimeBetweenBatches, health gating and maxSurge are recorded in the policy but not run; the instance-level update changes tags, protectionPolicy, licenseType, userData, diagnosticsProfile and additionalCapabilities, and other changed properties are refused. - ManagedIdentity: assignmentRestrictions and the api-versions 2025-01-31-preview and 2025-05-31-preview are not implemented; isolationScope is stored and echoed but never enforced; listAssociatedResources scans Compute, Web, Container Instances, Container Apps and AKS resources only; resource group deletion removes same-named groups of identities in every subscription. -- API Management: not modelled - the built-in all-access (master) subscription, the starter/unlimited products and built-in groups, diagnostics, certificates, gateways (self-hosted), portal, schemas, API revisions/releases, user subscriptions, wikis, issues, tenant settings, backup/restore, soft-delete/restore, custom hostnames, virtual networks, multi-region, private endpoints, v2 tiers (BasicV2, StandardV2) and the Isolated sku; they fall to 404 or are rejected. $top, $skip, count and nextLink paging work on the child lists; $filter is honoured on the APIs, API operations, product API, products, backends, named values (displayName only), tags, authorization servers, OpenID Connect providers, groups, users, subscriptions, loggers and policy fragment lists, and ignored on the other lists (the SDK documents no $filter for them). -- API Management gateway: policies outside the subset (validate-jwt, quota, cache, choose, set-variable, send-request, authentication-*, policy expressions, product-scope policies, on-error execution, rate-limit nested api/operation, forward-request http-version/continue-timeout/buffer-*/fail-on-error-status-code, cors terminate-unmatched-request) are refused at PUT or not honoured; the backend section runs set-header/set-query-parameter/set-backend-service/forward-request in order and a chain with no forward-request answers an empty 200. The cors policy page gives two defaults for terminate-unmatched-request (false in the attribute table, true in the usage notes), so unmatched simple requests proceed without CORS headers. set-header on Connection, Content-Length, Keep-Alive and Transfer-Encoding is accepted but those headers are never forwarded (Learn: they cannot be changed). -- API Management gateway: WebSocket and GraphQL APIs are served as plain HTTP passthrough (ws/wss serviceUrl answers 500); HTTP (non-TLS) calls are impossible because the ARM listener is HTTPS, so an API whose protocols exclude https answers 404; the gateway has no client-certificate, IP or JWT checks; failed upstream calls answer 502 where the real gateway answers 500 (unverified); the unknown-host 404 body Resource not found and the 503 body of a service that is still activating are gopherstack wording, not documented. +- API Management: not modelled - gateways (self-hosted), portal, user subscriptions, wikis, issues, tenant settings, backup/restore, soft-delete/restore, custom hostnames, virtual networks, multi-region, private endpoints, v2 tiers (BasicV2, StandardV2) and the Isolated sku; they fall to 404 or are rejected. $top, $skip, count and nextLink paging work on the child lists; $filter is honoured on the APIs, API operations, product API, products, backends, named values (displayName only), tags, authorization servers, OpenID Connect providers, groups, users, subscriptions, loggers and policy fragment lists, and ignored on the other lists (the SDK documents no $filter for them). +- API Management gateway: policies outside the subset (authentication-managed-identity, policy expressions beyond the documented subset, on-error for built-in pipeline errors such as a missing subscription key or an unmatched operation, rate-limit nested api/operation, forward-request http-version/continue-timeout/buffer-*/fail-on-error-status-code, cors terminate-unmatched-request) are refused at PUT or not honoured; the backend section runs set-header/set-query-parameter/set-backend-service/forward-request in order and a chain with no forward-request answers an empty 200. The cors policy page gives two defaults for terminate-unmatched-request (false in the attribute table, true in the usage notes), so unmatched simple requests proceed without CORS headers. set-header on Connection, Content-Length, Keep-Alive and Transfer-Encoding is accepted but those headers are never forwarded (Learn: they cannot be changed). +- API Management gateway: HTTP (non-TLS) calls are impossible because the ARM listener is HTTPS, so an API whose protocols exclude https answers 404; the gateway has no client-certificate checks (validate-client-certificate, context.Request.Certificate); failed upstream calls answer 502 where the real gateway answers 500 (unverified); the unknown-host 404 body Resource not found and the 503 body of a service that is still activating are gopherstack wording, not documented. - Authorization: with --azure-arm-enforce-rbac, ARM requests under a resource group are evaluated against the bearer token's role assignments (action derived as {namespace}/{type}/{read|write|delete|action}); data planes, subscription-level and management-group requests are not evaluated; there is no deny-assignment API because only Blueprints, managed applications and similar services create deny assignments and none is emulated, so evaluation has no deny source; no PIM/eligibility/schedule, classic administrator or provider-operations API, no management-group scope for locks, and management group scopes are accepted but never checked to exist; managed-identity token endpoints do not exist, so a system-assigned identity cannot obtain a token to be evaluated. - Authorization: ScopeLocked enforcement covers the ARM listener only (not data planes, as documented); it does not model the documented exceptions where services act on locked resources, resource moves, or Microsoft.Authorization extension resources other than the lock itself inheriting a lock (role assignments and policy assignments do inherit it). - Authorization: role assignment conditions (ABAC) are stored and validated (conditionVersion 2.0, balanced brackets) but never evaluated, because evaluation needs the request attributes of the data plane that carries the attribute namespaces; delegatedManagedIdentityResourceId is stored; the last-owner deletion guard does not exist; assignableScopes of management groups are not checked to exist; list calls are not paged (no nextLink/$skipToken). - Policy: deny, audit, append and modify are evaluated at write time (PUT of a resource group or resource) for rules that read type, name, id, location, kind and tags with parameters(), concat() and field(); rules that read aliases, requestContext() or resourceGroup() are skipped, as are auditIfNotExists, deployIfNotExists and denyAction, so no remediation, policy versions, tokens or allowed-locations deny on aliased types exist; compliance states are recorded per resource and definition and persisted, but there is no Microsoft.PolicyInsights read API because armpolicyinsights is not in the module cache; exemptions are honoured; policyDefinitions is limited to a 13-definition and 1-initiative built-in catalog; initiative parameters are not checked against their member definitions; the Guest Configuration provider does not exist. - Authorization: management-group scoped policy assignments have no Terraform fixture (azurerm_management_group needs a tenant-level group API the emulator does not model); azurerm_role_definition, subscription policy assignments and policy set definitions are applied, planned clean and destroyed by TestTerraform_Azure_AuthorizationScoped, and test/terraform/azure/flexible_test.go and apim_test.go cover the Flexible Server and API Management resources named there. -- Logic: not routed (answer 404 NotFound): workflows move, generateUpgradedDefinition and listSwagger, run operations, requestHistories and listExpressionTraces, and every Integration Account and Integration Service Environment API. -- Logic: only Request and Recurrence triggers fire. Http polling, HttpWebhook, Workflow and SlidingWindow triggers are stored but never run. -- Logic expression functions: date formatting and parsing know the en-US, fr-FR and es-ES names only; other locales are rejected. -- Logic: the Http action authenticates with Basic, Raw and ActiveDirectoryOAuth (Secret credential) only; ActiveDirectoryOAuth with the Certificate credential, ClientCertificate (no PFX client-certificate transport) and ManagedServiceIdentity (the emulator has no managed-identity token endpoint) are rejected. +- Logic: not routed (answer 404 NotFound): workflows move and generateUpgradedDefinition, and every Integration Account and Integration Service Environment API. +- Logic: only Request, Recurrence, Http polling and HttpWebhook triggers fire. SlidingWindow triggers are stored but never run (the Learn trigger reference has no section on it). +- Logic expression functions: date formatting and parsing know 19 cultures (en-US, en-GB, fr-FR, es-ES, de-DE, it-IT, pt-BR, pt-PT, nl-NL, sv-SE, da-DK, nb-NO, fi-FI, pl-PL, ja-JP, zh-CN, ko-KR, ru-RU, tr-TR); other locales are rejected. +- Logic: the Http action authenticates with Basic, Raw, ClientCertificate and ActiveDirectoryOAuth (Secret and Certificate credentials); ManagedServiceIdentity is rejected (the emulator has no managed-identity token endpoint the Logic provider can reuse). ### Deferred diff --git a/services/azurearm/apim_cache_test.go b/services/azurearm/apim_cache_test.go new file mode 100644 index 0000000000..fa198f0e29 --- /dev/null +++ b/services/azurearm/apim_cache_test.go @@ -0,0 +1,258 @@ +package azurearm_test + +import ( + "io" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/apimanagement/armapimanagement/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type countingBackend struct { + srv *httptest.Server + hits atomic.Int64 +} + +func newCountingBackend(t *testing.T) *countingBackend { + t.Helper() + + cb := &countingBackend{} + cb.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + n := cb.hits.Add(1) + _, _ = io.Copy(io.Discard, r.Body) + + w.Header().Set("X-Hit", strconv.FormatInt(n, 10)) + + if strings.HasSuffix(r.URL.Path, "/404") { + w.WriteHeader(http.StatusNotFound) + } + + _, _ = io.WriteString(w, "hit="+strconv.FormatInt(n, 10)) + })) + t.Cleanup(cb.srv.Close) + + return cb +} + +func (e *gwEnv) cacheAPI(t *testing.T) *countingBackend { + t.Helper() + + cb := newCountingBackend(t) + e.putAPI(t, "data", "data", cb.srv.URL) + e.putOp(t, "data", "get", "get", "/{id}") + e.putOp(t, "data", "post", "post", "/{id}") + + return cb +} + +func TestAPIMGateway_CacheLookupStore(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + cb := e.cacheAPI(t) + + e.policy( + t, + "/apis/data", + ` + vAccept + `, + http.StatusCreated, + ) + + get := func(path string, hdr map[string]string) (int, string, http.Header) { + return e.call(t, "GET", path, "", hdr) + } + + _, body, _ := get("/data/a?v=1", nil) + assert.Equal(t, "hit=1", body) + + _, body, hdr := get("/data/a?v=1&ignored=x", nil) + assert.Equal(t, "hit=1", body, "a non-varied query parameter shares the entry") + assert.Equal(t, "1", hdr.Get("X-Hit")) + + _, body, _ = get("/data/a?v=2", nil) + assert.Equal(t, "hit=2", body, "vary-by-query-parameter") + + _, body, _ = get("/data/a?v=1", map[string]string{"Accept": "text/csv"}) + assert.Equal(t, "hit=3", body, "vary-by-header") + + _, body, _ = e.call(t, "POST", "/data/a", "", nil) + assert.Equal(t, "hit=4", body) + + _, body, _ = e.call(t, "POST", "/data/a", "", nil) + assert.Equal(t, "hit=5", body, "only GET responses are cached") + + e.clock.Advance(61 * time.Second) + + _, body, _ = get("/data/a?v=1", nil) + assert.Equal(t, "hit=6", body, "the entry expired on the injected clock") + assert.Equal(t, int64(6), cb.hits.Load()) +} + +func TestAPIMGateway_CacheAuthorizedAndStatus(t *testing.T) { + t.Parallel() + + tests := []struct { //nolint:govet // test-only struct; layout not performance-critical + name string + storeAttr string + lookup string + path string + hdr map[string]string + wantHits int64 + }{ + {"authorized not cached", "", "", "/data/a", map[string]string{"Authorization": "Bearer x"}, 2}, + { + "private allowed", + "", + ` allow-private-response-caching="true"`, + "/data/a", + map[string]string{"Authorization": "Bearer x"}, + 1, + }, + { + "private expression", + "", + ` allow-private-response-caching="@(true)"`, + "/data/a", + map[string]string{"Authorization": "Bearer x"}, + 1, + }, + {"404 not cached by default", "", "", "/data/404", nil, 2}, + {"404 cached with cache-response", ` cache-response="true"`, "", "/data/404", nil, 1}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + cb := e.cacheAPI(t) + + e.policy( + t, + "/apis/data", + `Authorization + `, + http.StatusCreated, + ) + + e.call(t, "GET", tc.path, "", tc.hdr) + e.call(t, "GET", tc.path, "", tc.hdr) + assert.Equal(t, tc.wantHits, cb.hits.Load()) + }) + } +} + +func TestAPIMGateway_CacheDownstreamAndDeveloper(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + cb := e.cacheAPI(t) + + e.policy( + t, + "/apis/data", + ` + `, + http.StatusCreated, + ) + + mk := func(id, owner string) string { + _, err := e.f.NewSubscriptionClient().CreateOrUpdate(t.Context(), apimRG, apimSvc, id, + armapimanagement.SubscriptionCreateParameters{ + Properties: &armapimanagement.SubscriptionCreateParameterProperties{ + DisplayName: new(id), Scope: new("/apis"), OwnerID: new("/users/" + owner), + State: new(armapimanagement.SubscriptionStateActive), + }, + }, nil) + require.NoError(t, err) + + sec, err := e.f.NewSubscriptionClient().ListSecrets(t.Context(), apimRG, apimSvc, id, nil) + require.NoError(t, err) + + return *sec.PrimaryKey + } + + k1, k2 := mk("d1", "u1"), mk("d2", "u2") + + call := func(k string) (string, http.Header) { + _, body, hdr := e.call(t, "GET", "/data/a", "", map[string]string{"Ocp-Apim-Subscription-Key": k}) + + return body, hdr + } + + body, hdr := call(k1) + assert.Equal(t, "hit=1", body) + assert.Equal(t, "public, max-age=60", hdr.Get("Cache-Control")) + + body, hdr = call(k1) + assert.Equal(t, "hit=1", body) + assert.Equal(t, "public, max-age=60", hdr.Get("Cache-Control")) + + body, _ = call(k2) + assert.Equal(t, "hit=2", body, "vary-by-developer separates owners") + assert.Equal(t, int64(2), cb.hits.Load()) +} + +func TestAPIMGateway_CacheValue(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(` + `+ + headerPolicy("X-Cv", `@((string)context.Variables["cv"])`)+` + + + `, + "", ""), http.StatusCreated) + + get := func(q string) string { + _, body, _ := e.call(t, "GET", "/echo/items/1"+q, "", nil) + + return decodeEcho(t, body).Header["X-Cv"][0] + } + + assert.Equal(t, "none", get("?v=a")) + assert.Equal(t, "stored-a", get("?v=b")) + assert.Equal(t, "stored-b", get("")) + + e.clock.Advance(61 * time.Second) + assert.Equal(t, "none", get("?v=c"), "the value expired") + assert.Equal(t, "stored-c", get("?drop=1"), "lookup runs before the removal") +} + +func TestAPIMCache_Validation(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + tests := []struct{ name, in, out, want string }{ + {"store in inbound", ``, "", "not allowed in the inbound"}, + {"lookup in outbound", "", ``, "not allowed in the outbound"}, + {"store no duration", "", ``, "'duration' is required"}, + {"bad downstream", ``, "", "downstream-caching-type"}, + {"bad caching type", ``, "", "caching-type"}, + {"lookup-value no variable", ``, "", "'variable-name' is required"}, + {"bad bool", ``, "", "must-revalidate"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + body := e.policy(t, "/apis/echo", policyDoc(tc.in, "", tc.out), http.StatusBadRequest) + assert.Contains(t, body, tc.want) + }) + } +} diff --git a/services/azurearm/apim_entities_test.go b/services/azurearm/apim_entities_test.go index 91fbb4713b..8ed67d9140 100644 --- a/services/azurearm/apim_entities_test.go +++ b/services/azurearm/apim_entities_test.go @@ -575,7 +575,7 @@ func TestAPIMSubscription_SecretsAndKeys(t *testing.T) { } } - assert.Equal(t, 3, n) + assert.Equal(t, 4, n) } func TestAPIMNamedValue_SecretWriteOnly(t *testing.T) { diff --git a/services/azurearm/apim_expr_internal_test.go b/services/azurearm/apim_expr_internal_test.go new file mode 100644 index 0000000000..142a24556d --- /dev/null +++ b/services/azurearm/apim_expr_internal_test.go @@ -0,0 +1,101 @@ +package azurearm + +import ( + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type apimStubEnv struct{} + +func (apimStubEnv) member(_ any, name string) (any, error) { return "v-" + name, nil } +func (apimStubEnv) now() time.Time { return time.Unix(0, 0).UTC() } + +func apimEvalForTest(src string) (any, error) { + n, err := apimParseExpr(src) + if err != nil { + return nil, err + } + + return apimEvalExpr(n, apimStubEnv{}, &apimExprCounter{}) +} + +func TestAPIMExprInternal_Pathological(t *testing.T) { + t.Parallel() + + deepParen := strings.Repeat("(", 5000) + "1" + strings.Repeat(")", 5000) + deepNot := strings.Repeat("!", 5000) + "true" + deepNeg := strings.Repeat("-", 5000) + "1" + deepTernary := strings.Repeat("true ? ", 3000) + "1" + strings.Repeat(" : 2", 3000) + chain := "context" + strings.Repeat(".Request", 3000) + args := "string.Concat(" + strings.Repeat("1,", 5000) + "1)" + big := `"` + strings.Repeat("a", 3000) + `"` + doubling := big + strings.Repeat(" + "+big, 0) + + tests := []struct { + name string + src string + }{ + {"deep paren", deepParen}, + {"deep not", deepNot}, + {"deep neg", deepNeg}, + {"deep ternary", deepTernary}, + {"chain", chain}, + {"args", args}, + {"long literal", doubling}, + {"huge int", "99999999999999999999999999"}, + {"min int div", "(-9223372036854775807 - 1) / -1"}, + {"min int mod", "(-9223372036854775807 - 1) % -1"}, + {"unterminated", `"abc`}, + {"lone op", "&&"}, + {"nul", "\x00"}, + {"invalid utf8", "\xff\xfe"}, + {"empty", ""}, + {"index", `context.Request.Headers[`}, + {"generic", `context.Variables.GetValueOrDefault<`}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + assert.NotPanics(t, func() { _, _ = apimEvalForTest(tt.src) }) + }) + } +} + +func TestAPIMExprInternal_Doubling(t *testing.T) { + t.Parallel() + + // 12 concatenations of a 1000-char literal tree cannot exceed the string bound. + lit := `"` + strings.Repeat("a", 900) + `"` + expr := lit + for len(expr) < apimExprMaxLen/2 { + expr = "(" + expr + " + " + expr + ")" + } + + v, err := apimEvalForTest(expr) + if err == nil { + s, _ := v.(string) + assert.LessOrEqual(t, len(s), apimExprMaxString) + } + + require.NotPanics(t, func() { _, _ = apimEvalForTest(expr) }) +} + +func FuzzAPIMExpr(f *testing.F) { + for _, s := range []string{ + `"a" + "b"`, `1 + 2 * 3`, `true ? 1 : 2`, `context.Request.Method == "GET"`, + `(int)"5" + 1`, `null ?? "x"`, `!true || false && true`, `-5 % 3`, + `context.Variables.GetValueOrDefault("k", null)`, `"a".ToUpper().Length`, + } { + f.Add(s) + } + + f.Fuzz(func(_ *testing.T, src string) { + _, _ = apimEvalForTest(src) + }) +} diff --git a/services/azurearm/apim_expr_test.go b/services/azurearm/apim_expr_test.go new file mode 100644 index 0000000000..78291a1d9f --- /dev/null +++ b/services/azurearm/apim_expr_test.go @@ -0,0 +1,355 @@ +package azurearm_test + +import ( + "net/http" + "strings" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/apimanagement/armapimanagement/v2" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func headerPolicy(name, expr string) string { + return `` + expr + `` +} + +func TestAPIMExpr_Evaluator(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + cases := []struct{ name, expr, want string }{ + {"method", `@(context.Request.Method)`, "GET"}, + {"ternary", `@(context.Request.Method == "GET" ? "yes" : "no")`, "yes"}, + {"concat", `@("a" + "b" + 1)`, "ab1"}, + {"header default", `@(context.Request.Headers.GetValueOrDefault("X-In", "none"))`, "hello"}, + {"header missing", `@(context.Request.Headers.GetValueOrDefault("X-Missing", "none"))`, "none"}, + {"path", `@(context.Request.Url.Path)`, "/echo/items/7"}, + {"matched", `@(context.Request.MatchedParameters["id"])`, "7"}, + {"query", `@(context.Request.Url.Query.GetValueOrDefault("q", "d"))`, "z"}, + {"upper", `@(context.Request.Headers.GetValueOrDefault("X-In", "").ToUpper())`, "HELLO"}, + {"startswith", `@(context.Request.Headers.GetValueOrDefault("X-In", "").StartsWith("he"))`, "True"}, + { + "boolean ops", + `@(context.Request.Headers.GetValueOrDefault("X-In", "").EndsWith("lo") && ` + + `!context.Request.Headers.GetValueOrDefault("X-In", "").Contains("zz"))`, + "True", + }, + {"int parse", `@(int.Parse(context.Request.MatchedParameters["id"]) + 5)`, "12"}, + { + "ignore case", + `@(context.Request.Url.Path.Equals("/ECHO/items/7", StringComparison.OrdinalIgnoreCase))`, + "True", + }, + {"api", `@(context.Api.Id)`, "echo"}, + {"operation", `@(context.Operation.Id)`, "get-item"}, + {"subscription", `@(context.Subscription.Name)`, "k1"}, + {"ip", `@(context.Request.IpAddress)`, "127.0.0.1"}, + {"contains key", `@(context.Variables.ContainsKey("nope"))`, "False"}, + {"clock", `@(DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ").StartsWith("2026-01-01T01:"))`, "True"}, + {"guid", `@(Guid.NewGuid().ToString().Length)`, "36"}, + {"variable", `@((string)context.Variables["v"])`, "abc"}, + {"typed variable", `@((int)context.Variables["n"] + 1)`, "43"}, + {"generic default", `@(context.Variables.GetValueOrDefault("zz", 9))`, "9"}, + {"null coalesce", `@(context.Variables.GetValueOrDefault("zz", null) ?? "fallback")`, "fallback"}, + } + + var in strings.Builder + + in.WriteString(``) + + for i, c := range cases { + in.WriteString(headerPolicy("X-E"+string(rune('a'+i)), c.expr)) + } + + e.policy(t, "/apis/echo", policyDoc(in.String(), "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/7?q=z", "", map[string]string{"X-In": "hello"}) + require.Equal(t, http.StatusOK, status, body) + + got := decodeEcho(t, body) + + for i, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, []string{c.want}, got.Header["X-E"+string(rune('a'+i))], c.expr) + }) + } +} + +func TestAPIMExpr_RejectedAtPut(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + tests := []struct{ name, expr, want string }{ + {"foreign type", `@(System.IO.File.ReadAllText("x"))`, "'ReadAllText'"}, + {"multi statement", `@{ return "x"; }`, "Multi-statement"}, + {"body", `@(context.Request.Body.As())`, "context.Request.Body"}, + {"unknown context member", `@(context.Foo)`, "'Foo'"}, + {"syntax", `@(1 +)`, "unexpected token"}, + {"new", `@(new Object())`, "unexpected token"}, + {"regex", `@(Regex.IsMatch("a", "b"))`, "'IsMatch'"}, + {"unknown method", `@(context.Request.Headers.Foo())`, "'Foo'"}, + {"too deep", `@(` + strings.Repeat("(", 100) + "1" + strings.Repeat(")", 100) + `)`, "nested too deeply"}, + {"too long", `@("` + strings.Repeat("a", 5000) + `")`, "longer than"}, + {"unterminated", `@(context.Request.Method`, "Multi-statement"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + body := e.policy(t, "/apis/echo", policyDoc(headerPolicy("X-A", tc.expr), "", ""), http.StatusBadRequest) + assert.Contains(t, body, "ValidationError") + assert.Contains(t, body, tc.want) + }) + } +} + +func TestAPIMPolicy_ChooseValidation(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + tests := []struct{ name, doc, want string }{ + {"no when", ``, "at least one when"}, + { + "otherwise first", + ``, + "followed by at most one otherwise", + }, + {"bad condition", ``, "boolean expression or constant"}, + {"missing condition", ``, "'condition' is required"}, + {"base inside", ``, "not allowed inside choose"}, + {"nested unsupported", ``, "json-to-xml"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + body := e.policy(t, "/apis/echo", policyDoc(tc.doc, "", ""), http.StatusBadRequest) + assert.Contains(t, body, tc.want) + }) + } +} + +func TestAPIMGateway_Choose(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + doc := policyDoc(` + + + `+headerPolicy("X-Kind", "mobile")+` + + `+headerPolicy("X-Kind", "beta")+` + + `+headerPolicy("X-Kind", "desktop")+` + `, "", "") + e.policy(t, "/apis/echo", doc, http.StatusCreated) + + tests := []struct { + name, path, ua, want string + }{ + {"mobile", "/echo/items/1", "iPhone", "mobile"}, + {"nested beta", "/echo/items/1?beta=1", "curl", "beta"}, + {"otherwise", "/echo/items/1", "curl", "desktop"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + status, body, _ := e.call(t, "GET", tc.path, "", map[string]string{"User-Agent": tc.ua}) + require.Equal(t, http.StatusOK, status, body) + assert.Equal(t, []string{tc.want}, decodeEcho(t, body).Header["X-Kind"]) + }) + } +} + +func TestAPIMGateway_ChooseReturnResponse(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(` + nope + `, "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/1?deny=1", "", nil) + assert.Equal(t, http.StatusForbidden, status) + assert.Equal(t, "nope", body) + + status, _, _ = e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, http.StatusOK, status) +} + +func TestAPIMGateway_OnError(t *testing.T) { + t.Parallel() + + onErr := `@(context.LastError.Source) + @(context.LastError.Reason) + @(context.LastError.Section) + @(context.LastError.Scope) + + @(context.Response.StatusCode.ToString())` + + t.Run("rate limit", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy( + t, + "/apis/echo", + ""+ + ""+onErr+"", + http.StatusCreated, + ) + + status, _, _ := e.call(t, "GET", "/echo/items/1", "", nil) + require.Equal(t, http.StatusOK, status) + + status, body, hdr := e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, http.StatusTooManyRequests, status, body) + assert.Equal(t, "rate-limit", hdr.Get("X-Source")) + assert.Equal(t, "RateLimitExceeded", hdr.Get("X-Reason")) + assert.Equal(t, "inbound", hdr.Get("X-Section")) + assert.Equal(t, "api", hdr.Get("X-Scope")) + assert.Equal(t, "429", hdr.Get("X-Status")) + }) + + t.Run("expression failure", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy( + t, + "/apis/echo", + ""+ + ""+onErr+"", + http.StatusCreated, + ) + + status, body, hdr := e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, http.StatusInternalServerError, status, body) + assert.Equal(t, "set-variable", hdr.Get("X-Source")) + assert.Equal(t, "ExpressionValueEvaluationFailure", hdr.Get("X-Reason")) + }) + + t.Run("return response replaces error", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy( + t, + "/apis/echo", + ""+ + ""+ + ``+ + `@("handled:" + context.LastError.Reason)`+ + "", + http.StatusCreated, + ) + + e.call(t, "GET", "/echo/items/1", "", nil) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, 299, status) + assert.Equal(t, "handled:RateLimitExceeded", body) + }) + + t.Run("backend failure", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putAPI(t, "dead", "dead", "http://example.invalid") + e.putOp(t, "dead", "g", "get", "/x") + e.policy( + t, + "/apis/dead", + ""+ + ""+onErr+"", + http.StatusCreated, + ) + + status, _, hdr := e.call(t, "GET", "/dead/x", "", nil) + assert.Equal(t, http.StatusBadGateway, status) + assert.Equal(t, "forward-request", hdr.Get("X-Source")) + assert.Equal(t, "BackendConnectionFailure", hdr.Get("X-Reason")) + assert.Equal(t, "backend", hdr.Get("X-Section")) + }) +} + +func TestAPIMGateway_ProductScopePolicy(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putProduct(t, "gold", false) + e.linkProductAPI(t, "gold", "echo") + key := e.productSubscription(t, "goldsub", "gold") + + e.policy(t, "", policyDoc(headerPolicy("X-Global", "g"), "", ""), http.StatusCreated) + e.policy( + t, + "/products/gold", + policyDoc(headerPolicy("X-Product", `@(context.Product.Id)`), "", ""), + http.StatusCreated, + ) + e.policy(t, "/apis/echo", policyDoc(headerPolicy("X-Api", "a"), "", ""), http.StatusCreated) + e.policy(t, "/apis/echo/operations/get-item", policyDoc(headerPolicy("X-Op", "o"), "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"Ocp-Apim-Subscription-Key": key}) + require.Equal(t, http.StatusOK, status, body) + + h := decodeEcho(t, body).Header + assert.Equal(t, []string{"g"}, h["X-Global"]) + assert.Equal(t, []string{"gold"}, h["X-Product"]) + assert.Equal(t, []string{"a"}, h["X-Api"]) + assert.Equal(t, []string{"o"}, h["X-Op"]) + + status, body, _ = e.call(t, "GET", "/echo/items/1", "", nil) + require.Equal(t, http.StatusOK, status, body) + assert.Empty(t, decodeEcho(t, body).Header["X-Product"], "the all-APIs subscription belongs to no product") +} + +func (e *gwEnv) putProduct(t *testing.T, id string, subscriptionRequired bool) { + t.Helper() + + _, err := e.f.NewProductClient().CreateOrUpdate(t.Context(), apimRG, apimSvc, id, armapimanagement.ProductContract{ + Properties: &armapimanagement.ProductContractProperties{ + DisplayName: new(id), SubscriptionRequired: new(subscriptionRequired), + State: new(armapimanagement.ProductStatePublished), + }, + }, nil) + require.NoError(t, err) +} + +func (e *gwEnv) linkProductAPI(t *testing.T, product, api string) { + t.Helper() + + _, err := e.f.NewProductAPIClient().CreateOrUpdate(t.Context(), apimRG, apimSvc, product, api, nil) + require.NoError(t, err) +} + +func (e *gwEnv) productSubscription(t *testing.T, id, product string) string { + t.Helper() + + _, err := e.f.NewSubscriptionClient().CreateOrUpdate(t.Context(), apimRG, apimSvc, id, + armapimanagement.SubscriptionCreateParameters{ + Properties: &armapimanagement.SubscriptionCreateParameterProperties{ + DisplayName: new(id), Scope: new("/products/" + product), + State: new(armapimanagement.SubscriptionStateActive), + }, + }, nil) + require.NoError(t, err) + + sec, err := e.f.NewSubscriptionClient().ListSecrets(t.Context(), apimRG, apimSvc, id, nil) + require.NoError(t, err) + + return *sec.PrimaryKey +} diff --git a/services/azurearm/apim_gateway_test.go b/services/azurearm/apim_gateway_test.go index 668cecc2d0..10cbaffb05 100644 --- a/services/azurearm/apim_gateway_test.go +++ b/services/azurearm/apim_gateway_test.go @@ -1,7 +1,6 @@ package azurearm_test import ( - "context" "encoding/json/jsontext" "encoding/json/v2" "io" @@ -485,11 +484,11 @@ func TestAPIMGateway_Persistence(t *testing.T) { http.StatusCreated, ) - data := e.handler.Snapshot(context.Background()) + data := e.handler.Snapshot(t.Context()) require.NotEmpty(t, data) fresh := newAPIMStack(t) - require.NoError(t, fresh.handler.Restore(context.Background(), data)) + require.NoError(t, fresh.handler.Restore(t.Context(), data)) fresh.clock.Advance(2 * time.Hour) got, err := fresh.f.NewServiceClient().Get(t.Context(), apimRG, apimSvc, nil) @@ -517,7 +516,7 @@ func TestAPIMGateway_Persistence(t *testing.T) { assert.Equal(t, 3, ops) empty := newAPIMStack(t) - require.NoError(t, fresh.handler.Restore(context.Background(), empty.handler.Snapshot(context.Background()))) + require.NoError(t, fresh.handler.Restore(t.Context(), empty.handler.Snapshot(t.Context()))) _, err = fresh.f.NewServiceClient().Get(t.Context(), apimRG, apimSvc, nil) require.Error(t, err) diff --git a/services/azurearm/apim_jwt_test.go b/services/azurearm/apim_jwt_test.go new file mode 100644 index 0000000000..351e21aa14 --- /dev/null +++ b/services/azurearm/apim_jwt_test.go @@ -0,0 +1,443 @@ +package azurearm_test + +import ( + "crypto/rand" + "crypto/rsa" + "encoding/base64" + "encoding/json/v2" + "math/big" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const onErrReason = `` + + `@(context.LastError.Reason)` + +func jwtPolicy(inbound string) string { + return "" + inbound + `` + + onErrReason + "" +} + +func signingKey(k string) string { + return `` + k + `` +} + +func signHS(t *testing.T, alg jwt.SigningMethod, secret []byte, claims jwt.MapClaims) string { + t.Helper() + + s, err := jwt.NewWithClaims(alg, claims).SignedString(secret) + require.NoError(t, err) + + return s +} + +func TestAPIMGateway_ValidateJWTSymmetric(t *testing.T) { + t.Parallel() + + secret := []byte("0123456789abcdef0123456789abcdef") + e := newGWEnv(t) + now := e.clock.Now() + + e.policy(t, "/apis/echo", jwtPolicy(` + `+base64.StdEncoding.EncodeToString(secret)+` + api://xiss1 + adminops + `+headerPolicy("X-Sub", `@(((Jwt)context.Variables["jwt"]).Subject)`)), http.StatusCreated) + + good := func(over jwt.MapClaims) jwt.MapClaims { + c := jwt.MapClaims{ + "sub": "s1", "aud": "api://x", "iss": "iss1", "role": []string{"ops"}, + "exp": now.Add(time.Hour).Unix(), + } + for k, v := range over { + if v == nil { + delete(c, k) + + continue + } + + c[k] = v + } + + return c + } + + other := []byte("ffffffffffffffffffffffffffffffff") + noneTok, err := jwt.NewWithClaims(jwt.SigningMethodNone, good(nil)).SignedString(jwt.UnsafeAllowNoneSignatureType) + require.NoError(t, err) + + tests := []struct { //nolint:govet // test-only struct; layout not performance-critical + name string + auth string + wantStatus int + wantReason string + }{ + {"valid hs256", "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(nil)), 200, ""}, + {"valid hs384", "Bearer " + signHS(t, jwt.SigningMethodHS384, secret, good(nil)), 200, ""}, + {"valid hs512", "Bearer " + signHS(t, jwt.SigningMethodHS512, secret, good(nil)), 200, ""}, + { + "within clock skew", + "Bearer " + signHS( + t, + jwt.SigningMethodHS256, + secret, + good(jwt.MapClaims{"exp": now.Add(-10 * time.Second).Unix()}), + ), + 200, + "", + }, + { + "expired", + "Bearer " + signHS( + t, + jwt.SigningMethodHS256, + secret, + good(jwt.MapClaims{"exp": now.Add(-time.Minute).Unix()}), + ), + 401, + "TokenExpired", + }, + { + "no exp", + "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(jwt.MapClaims{"exp": nil})), + 401, + "JwtInvalid", + }, + {"wrong key", "Bearer " + signHS(t, jwt.SigningMethodHS256, other, good(nil)), 401, "TokenSignatureInvalid"}, + {"alg none", "Bearer " + noneTok, 401, "TokenSignatureInvalid"}, + { + "wrong audience", + "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(jwt.MapClaims{"aud": "other"})), + 401, + "TokenAudienceNotAllowed", + }, + { + "wrong issuer", + "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(jwt.MapClaims{"iss": "evil"})), + 401, + "TokenIssuerNotAllowed", + }, + { + "missing claim", + "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(jwt.MapClaims{"role": nil})), + 401, + "TokenClaimNotFound", + }, + { + "claim value", + "Bearer " + signHS(t, jwt.SigningMethodHS256, secret, good(jwt.MapClaims{"role": []string{"guest"}})), + 401, + "TokenClaimValueNotAllowed", + }, + {"no token", "", 401, "TokenNotPresent"}, + {"wrong scheme", "Basic " + signHS(t, jwt.SigningMethodHS256, secret, good(nil)), 401, "TokenNotPresent"}, + {"garbage", "Bearer not.a.jwt", 401, "JwtInvalid"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + status, body, hdr := e.call(t, "GET", "/echo/items/1", "", map[string]string{"Authorization": tc.auth}) + require.Equal(t, tc.wantStatus, status, body) + + if tc.wantStatus == 200 { + assert.Equal(t, []string{"s1"}, decodeEcho(t, body).Header["X-Sub"]) + + return + } + + assert.Equal(t, tc.wantReason, hdr.Get("X-Reason")) + }) + } +} + +func TestAPIMGateway_ValidateJWTSources(t *testing.T) { + t.Parallel() + + secret := []byte("0123456789abcdef0123456789abcdef") + k := base64.StdEncoding.EncodeToString(secret) + e := newGWEnv(t) + tok := signHS(t, jwt.SigningMethodHS256, secret, jwt.MapClaims{"exp": e.clock.Now().Add(time.Hour).Unix()}) + + tests := []struct { //nolint:govet // test-only struct; layout not performance-critical + name string + policy string + path string + hdr map[string]string + wantStatus int + wantBody string + }{ + { + "query parameter", + `` + signingKey(k) + ``, + "/echo/items/1?tok=" + tok, + nil, + 200, + "", + }, + { + "token-value expression", + `` + + signingKey(k) + ``, + "/echo/items/1", map[string]string{"X-T": tok}, 200, "", + }, + { + "custom failure", + `` + signingKey(k) + ``, + "/echo/items/1", map[string]string{"X-T": "x.y.z"}, 403, "denied here", + }, + { + "unsigned allowed when explicitly not required", + ``, + "/echo/items/1", map[string]string{"X-T": unsignedToken(t)}, 200, "", + }, + { + "unsigned refused by default", + `` + signingKey(k) + ``, + "/echo/items/1", map[string]string{"X-T": unsignedToken(t)}, 401, "", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + env := newGWEnv(t) + env.policy(t, "/apis/echo", jwtPolicy(tc.policy), http.StatusCreated) + + status, body, _ := env.call(t, "GET", tc.path, "", tc.hdr) + assert.Equal(t, tc.wantStatus, status, body) + assert.Contains(t, body, tc.wantBody) + }) + } +} + +func unsignedToken(t *testing.T) string { + t.Helper() + + s, err := jwt.NewWithClaims(jwt.SigningMethodNone, jwt.MapClaims{"sub": "x"}). + SignedString(jwt.UnsafeAllowNoneSignatureType) + require.NoError(t, err) + + return s +} + +func b64(b *big.Int) string { return base64.RawURLEncoding.EncodeToString(b.Bytes()) } + +func TestAPIMGateway_ValidateJWTAlgorithmConfusion(t *testing.T) { + t.Parallel() + + priv, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + e := newGWEnv(t) + exp := e.clock.Now().Add(time.Hour).Unix() + + e.policy(t, "/apis/echo", jwtPolicy(``), http.StatusCreated) + + rs := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"exp": exp}) + good, err := rs.SignedString(priv) + require.NoError(t, err) + + confused := signHS(t, jwt.SigningMethodHS256, priv.N.Bytes(), jwt.MapClaims{"exp": exp}) + + for name, tc := range map[string]struct { + tok string + want int + }{"rs256": {good, 200}, "hs256 with the public modulus as secret": {confused, 401}} { + t.Run(name, func(t *testing.T) { + t.Parallel() + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": tc.tok}) + assert.Equal(t, tc.want, status, body) + }) + } +} + +type jwksServer struct { + srv *httptest.Server + keys map[string]*rsa.PublicKey + issuer string + mu sync.Mutex + jwksFetch atomic.Int64 +} + +func newJWKSServer(t *testing.T, issuer string) *jwksServer { + t.Helper() + + js := &jwksServer{keys: map[string]*rsa.PublicKey{}, issuer: issuer} + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + _ = json.MarshalWrite(w, map[string]string{"issuer": issuer, "jwks_uri": js.srv.URL + "/jwks"}, jsonx.V1()) + }) + mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) { + js.jwksFetch.Add(1) + js.mu.Lock() + defer js.mu.Unlock() + + keys := make([]map[string]string, 0, len(js.keys)) + for kid, pk := range js.keys { + keys = append( + keys, + map[string]string{"kty": "RSA", "kid": kid, "n": b64(pk.N), "e": b64(big.NewInt(int64(pk.E)))}, + ) + } + + _ = json.MarshalWrite(w, map[string]any{"keys": keys}, jsonx.V1()) + }) + js.srv = httptest.NewServer(mux) + t.Cleanup(js.srv.Close) + + return js +} + +func (j *jwksServer) add(kid string, pk *rsa.PublicKey) { + j.mu.Lock() + j.keys[kid] = pk + j.mu.Unlock() +} + +func TestAPIMGateway_ValidateJWTOpenIDConfig(t *testing.T) { + t.Parallel() + + k1, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + k2, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + js := newJWKSServer(t, "https://issuer.example/") + js.add("k1", &k1.PublicKey) + + e := newGWEnv(t) + exp := e.clock.Now().Add(time.Hour).Unix() + + e.policy(t, "/apis/echo", jwtPolicy(``), http.StatusCreated) + + sign := func(kid string, key *rsa.PrivateKey, iss string) string { + tok := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"exp": exp, "iss": iss}) + tok.Header["kid"] = kid + + s, serr := tok.SignedString(key) + require.NoError(t, serr) + + return s + } + + call := func(tok string) int { + status, _, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": tok}) + + return status + } + + assert.Equal(t, 200, call(sign("k1", k1, "https://issuer.example/"))) + assert.Equal(t, 200, call(sign("k1", k1, "https://issuer.example/"))) + assert.Equal(t, int64(1), js.jwksFetch.Load(), "the JWKS is cached") + + assert.Equal(t, 401, call(sign("k1", k1, "https://evil/")), "the issuer comes from the configuration") + + js.add("k2", &k2.PublicKey) + assert.Equal( + t, + 401, + call(sign("k2", k2, "https://issuer.example/")), + "an unknown kid does not refetch within 5 minutes", + ) + assert.Equal(t, int64(1), js.jwksFetch.Load()) + + e.clock.Advance(6 * time.Minute) + + exp = e.clock.Now().Add(time.Hour).Unix() + assert.Equal(t, 200, call(sign("k2", k2, "https://issuer.example/")), "the refresh picks up the rotated key") + assert.Equal(t, int64(2), js.jwksFetch.Load()) +} + +func TestAPIMJWT_Validation(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + key := `` + base64.StdEncoding.EncodeToString( + []byte("0123456789abcdef"), + ) + `` + + tests := []struct{ name, stmt, want string }{ + {"no source", `` + key + ``, "Exactly one of"}, + { + "two sources", + `` + key + ``, + "Exactly one of", + }, + {"no keys", ``, "openid-config or issuer-signing-keys"}, + { + "bad http code", + `` + key + ``, + "'failed-validation-httpcode'", + }, + { + "bad boolean", + `` + key + ``, + "require-signed-tokens", + }, + { + "decryption keys", + `` + key + `QQ==`, + "not supported inside", + }, + { + "bad base64", + `!!!`, + "not valid Base64", + }, + { + "n without e", + ``, + "given together", + }, + { + "bad match", + `` + key + + ``, + "'match'", + }, + { + "bad openid url", + ``, + "absolute http or https", + }, + { + "certificate-id", + ``, + "does not exist", + }, + {"in outbound", "", "not allowed in the outbound"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + doc := policyDoc(tc.stmt, "", "") + if tc.stmt == "" { + doc = policyDoc("", "", ``+key+``) + } + + body := e.policy(t, "/apis/echo", doc, http.StatusBadRequest) + assert.Contains(t, body, tc.want) + }) + } +} diff --git a/services/azurearm/apim_mgmt_test.go b/services/azurearm/apim_mgmt_test.go new file mode 100644 index 0000000000..1a17dc1ef4 --- /dev/null +++ b/services/azurearm/apim_mgmt_test.go @@ -0,0 +1,698 @@ +package azurearm_test + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha1" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/hex" + "encoding/json/v2" + "io" + "math/big" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/apimanagement/armapimanagement/v2" + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "software.sslmate.com/src/go-pkcs12" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +func testCert(t *testing.T, cn string, notAfter time.Time) ([]byte, []byte) { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + tpl := &x509.Certificate{ + SerialNumber: big.NewInt(7), Subject: pkix.Name{CommonName: cn}, + NotBefore: notAfter.Add(-time.Hour), NotAfter: notAfter, + } + der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + pfx, err := pkcs12.Modern.Encode(key, cert, nil, "pw") + require.NoError(t, err) + + return der, pfx +} + +func TestAPIMBuiltins(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putAPI(t, "stp", "stp", e.backend.URL) + e.putOp(t, "stp", "g", "get", "/x") + e.linkProductAPI(t, "starter", "stp") + + groups := map[string]bool{} + pager := e.f.NewGroupClient().NewListByServicePager(apimRG, apimSvc, nil) + + for pager.More() { + page, err := pager.NextPage(t.Context()) + require.NoError(t, err) + + for _, g := range page.Value { + assert.Equal(t, armapimanagement.GroupTypeSystem, *g.Properties.Type) + assert.True(t, *g.Properties.BuiltIn) + + groups[*g.Name] = true + } + } + + assert.Equal(t, map[string]bool{"administrators": true, "developers": true, "guests": true}, groups) + + prods := map[string]string{} + pp := e.f.NewProductClient().NewListByServicePager(apimRG, apimSvc, nil) + + for pp.More() { + page, err := pp.NextPage(t.Context()) + require.NoError(t, err) + + for _, p := range page.Value { + prods[*p.Name] = *p.Properties.DisplayName + assert.Equal(t, armapimanagement.ProductStatePublished, *p.Properties.State) + } + } + + assert.Equal(t, map[string]string{"starter": "Starter", "unlimited": "Unlimited"}, prods) + + master, err := e.f.NewSubscriptionClient().Get(t.Context(), apimRG, apimSvc, "master", nil) + require.NoError(t, err) + assert.Equal(t, "Built-in all-access subscription", *master.Properties.DisplayName) + assert.Equal(t, armapimanagement.SubscriptionStateActive, *master.Properties.State) + assert.True(t, strings.HasSuffix(*master.Properties.Scope, "/"+apimSvc+"/"), *master.Properties.Scope) + + sec, err := e.f.NewSubscriptionClient().ListSecrets(t.Context(), apimRG, apimSvc, "master", nil) + require.NoError(t, err) + + status, body, _ := e.call(t, "GET", "/stp/x", "", map[string]string{"Ocp-Apim-Subscription-Key": *sec.PrimaryKey}) + assert.Equal(t, http.StatusOK, status, body) + + status, body, _ = e.raw( + t, + http.MethodDelete, + e.armPath("/subscriptions/master"), + "", + map[string]string{"If-Match": "*"}, + ) + assert.Equal(t, http.StatusBadRequest, status, body) + + status, body, _ = e.raw(t, http.MethodDelete, e.armPath("/groups/guests"), "", map[string]string{"If-Match": "*"}) + assert.Equal(t, http.StatusBadRequest, status, body) +} + +func TestAPIMBuiltins_StarterPolicyEnforced(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putAPI(t, "stp", "stp", e.backend.URL) + e.putOp(t, "stp", "g", "get", "/x") + e.linkProductAPI(t, "starter", "stp") + + key := e.productSubscription(t, "ss", "starter") + + for i := range 5 { + status, body, _ := e.call(t, "GET", "/stp/x", "", map[string]string{"Ocp-Apim-Subscription-Key": key}) + require.Equal(t, http.StatusOK, status, "call %d: %s", i, body) + } + + status, body, _ := e.call(t, "GET", "/stp/x", "", map[string]string{"Ocp-Apim-Subscription-Key": key}) + assert.Equal(t, http.StatusTooManyRequests, status, "the Starter product allows 5 calls a minute: %s", body) +} + +func TestAPIMBuiltins_ConsumptionHasNoClassicProducts(t *testing.T) { + t.Parallel() + + s := newAPIMStack(t) + s.createService(t, apimSvc, armapimanagement.SKUTypeConsumption, 0) + + n := 0 + pager := s.f.NewProductClient().NewListByServicePager(apimRG, apimSvc, nil) + + for pager.More() { + page, err := pager.NextPage(t.Context()) + require.NoError(t, err) + + n += len(page.Value) + } + + assert.Zero(t, n) + + _, err := s.f.NewSubscriptionClient().Get(t.Context(), apimRG, apimSvc, "master", nil) + require.NoError(t, err) +} + +func TestAPIMCertificates(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + notAfter := time.Date(2030, 5, 6, 7, 8, 9, 0, time.UTC) + der, pfx := testCert(t, "gw.example", notAfter) + sum := sha1.Sum(der) + wantThumb := strings.ToUpper(hex.EncodeToString(sum[:])) + + cc := e.f.NewCertificateClient() + put := func(id, data, pw string) (armapimanagement.CertificateClientCreateOrUpdateResponse, error) { + return cc.CreateOrUpdate(t.Context(), apimRG, apimSvc, id, armapimanagement.CertificateCreateOrUpdateParameters{ + Properties: &armapimanagement.CertificateCreateOrUpdateProperties{Data: &data, Password: &pw}, + }, nil) + } + + tests := []struct { + name, id, data, pw string + wantErr bool + }{ + {"pfx", "c1", base64.StdEncoding.EncodeToString(pfx), "pw", false}, + {"cer", "c2", base64.StdEncoding.EncodeToString(der), "", false}, + {"wrong password", "c3", base64.StdEncoding.EncodeToString(pfx), "nope", true}, + {"not base64", "c4", "!!!", "", true}, + {"garbage", "c5", base64.StdEncoding.EncodeToString([]byte("not a certificate")), "", true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + res, err := put(tc.id, tc.data, tc.pw) + if tc.wantErr { + require.Error(t, err) + + return + } + + require.NoError(t, err) + assert.Equal(t, wantThumb, *res.Properties.Thumbprint) + assert.Equal(t, "CN=gw.example", *res.Properties.Subject) + assert.True(t, notAfter.Equal(*res.Properties.ExpirationDate), "%v", res.Properties.ExpirationDate) + }) + } +} + +func TestAPIMCertificates_NeverEchoed(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + _, pfx := testCert(t, "gw.example", time.Date(2030, 5, 6, 7, 8, 9, 0, time.UTC)) + data := base64.StdEncoding.EncodeToString(pfx) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/certificates/c1"), + `{"properties":{"data":"`+data+`","password":"pw"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + status, body, _ = e.raw(t, http.MethodGet, e.armPath("/certificates/c1"), "", nil) + require.Equal(t, http.StatusOK, status, body) + assert.NotContains(t, body, data, "the uploaded data is never echoed") + assert.NotContains(t, body, `"password"`) + + status, body, _ = e.raw(t, http.MethodPut, e.armPath("/certificates/c1"), + `{"properties":{"keyVault":{"secretIdentifier":"https://v/secrets/s"}}}`, nil) + assert.Equal(t, http.StatusBadRequest, status, body) +} + +func TestAPIMDiagnostics(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/loggers/ai"), + `{"properties":{"loggerType":"applicationInsights","credentials":{"instrumentationKey":"k"}}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + tests := []struct { + name, path, body string + want int + }{ + { + "service ok", + "/diagnostics/applicationinsights", + `{"properties":{"loggerId":"/loggers/ai","alwaysLog":"allErrors",` + + `"sampling":{"samplingType":"fixed","percentage":50},"verbosity":"error","logClientIp":true,` + + `"httpCorrelationProtocol":"W3C","operationNameFormat":"Url",` + + `"frontend":{"request":{"headers":["a"],"body":{"bytes":100}}}}}`, + http.StatusCreated, + }, + { + "api ok", + "/apis/echo/diagnostics/applicationinsights", + `{"properties":{"loggerId":"/loggers/ai"}}`, + http.StatusCreated, + }, + {"no logger id", "/diagnostics/d1", `{"properties":{}}`, http.StatusBadRequest}, + {"unknown logger", "/diagnostics/d2", `{"properties":{"loggerId":"/loggers/ghost"}}`, http.StatusBadRequest}, + { + "bad sampling", + "/diagnostics/d3", + `{"properties":{"loggerId":"/loggers/ai","sampling":{"percentage":101}}}`, + http.StatusBadRequest, + }, + { + "bad verbosity", + "/diagnostics/d4", + `{"properties":{"loggerId":"/loggers/ai","verbosity":"loud"}}`, + http.StatusBadRequest, + }, + { + "bad body bytes", + "/diagnostics/d5", + `{"properties":{"loggerId":"/loggers/ai","backend":{"response":{"body":{"bytes":9000}}}}}`, + http.StatusBadRequest, + }, + { + "api unknown", + "/apis/ghost/diagnostics/applicationinsights", + `{"properties":{"loggerId":"/loggers/ai"}}`, + http.StatusNotFound, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + st, resp, _ := e.raw(t, http.MethodPut, e.armPath(tc.path), tc.body, nil) + assert.Equal(t, tc.want, st, resp) + }) + } +} + +func TestAPIMSchemas(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + tests := []struct { + name, path, body string + want int + }{ + { + "global json", + "/schemas/s1", + `{"properties":{"schemaType":"json","value":"{\"type\":\"object\"}"}}`, + http.StatusCreated, + }, + { + "global xml", + "/schemas/s2", + `{"properties":{"schemaType":"xml","value":""}}`, + http.StatusCreated, + }, + { + "global bad json", + "/schemas/s3", + `{"properties":{"schemaType":"json","value":"{nope"}}`, + http.StatusBadRequest, + }, + {"global bad xml", "/schemas/s4", `{"properties":{"schemaType":"xml","value":""}}`, http.StatusBadRequest}, + {"global bad type", "/schemas/s5", `{"properties":{"schemaType":"yaml","value":"x"}}`, http.StatusBadRequest}, + {"global no body", "/schemas/s6", `{"properties":{"schemaType":"json"}}`, http.StatusBadRequest}, + { + "api openapi", + "/apis/echo/schemas/a1", + `{"properties":{"contentType":"application/vnd.oai.openapi.components+json",` + + `"document":{"components":{"schemas":{"X":{"type":"string"}}}}}}`, + http.StatusCreated, + }, + { + "api graphql", + "/apis/echo/schemas/a2", + `{"properties":{"contentType":"application/vnd.ms-azure-apim.graphql.schema",` + + `"document":{"value":"type Query { a: Int }"}}}`, + http.StatusCreated, + }, + { + "api no document", + "/apis/echo/schemas/a3", + `{"properties":{"contentType":"application/json"}}`, + http.StatusBadRequest, + }, + { + "api bad content type", + "/apis/echo/schemas/a4", + `{"properties":{"contentType":"nonsense","document":{"value":"x"}}}`, + http.StatusBadRequest, + }, + { + "api bad xml", + "/apis/echo/schemas/a5", + `{"properties":{"contentType":"application/vnd.ms-azure-apim.xsd+xml","document":{"value":"f1 + + f2`, + ) + require.Less(t, status, http.StatusBadRequest, body) + + e.policy(t, "/apis/echo", policyDoc(``, "", ""), http.StatusCreated) + + status, body, _ = e.call(t, "GET", "/echo/items/1", "", nil) + require.Equal(t, http.StatusOK, status, body) + + h := decodeEcho(t, body).Header + assert.Equal(t, []string{"f1"}, h["X-Frag"]) + assert.Equal(t, []string{"f2"}, h["X-Frag2"]) + + body = e.policy( + t, + "/apis/echo", + policyDoc(``, "", ""), + http.StatusBadRequest, + ) + assert.Contains(t, body, "'ghost'") + + for name, doc := range map[string]string{ + "wrong root": ``, "nested": ``, + "unsupported": ``, "base": ``, + } { + status, body = frag("bad", doc) + assert.Equal(t, http.StatusBadRequest, status, name+": "+body) + } +} + +func jsonString(s string) string { + var sb strings.Builder + + sb.WriteByte('"') + + for _, r := range s { + switch r { + case '"': + sb.WriteString(`\"`) + case '\\': + sb.WriteString(`\\`) + case '\n', '\t': + sb.WriteByte(' ') + default: + sb.WriteRune(r) + } + } + + sb.WriteByte('"') + + return sb.String() +} + +func TestAPIMMgmtPersistence(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + der, _ := testCert(t, "persist.example", time.Date(2031, 1, 1, 0, 0, 0, 0, time.UTC)) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/certificates/pc"), + `{"properties":{"data":"`+base64.StdEncoding.EncodeToString(der)+`"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + for _, w := range []struct{ path, body string }{ + {"/loggers/ai", `{"properties":{"loggerType":"applicationInsights",` + + `"credentials":{"instrumentationKey":"k"}}}`}, + {"/diagnostics/applicationinsights", `{"properties":{"loggerId":"/loggers/ai"}}`}, + {"/schemas/gs", `{"properties":{"schemaType":"json","value":"{}"}}`}, + {"/apis/echo/schemas/as", `{"properties":{"contentType":"application/json","document":{"value":"{}"}}}`}, + {"/products/starter/policies/policy", `{"properties":{"format":"xml",` + + `"value":""}}`}, + } { + path, b := w.path, w.body + status, body, _ = e.raw(t, http.MethodPut, e.armPath(path), b, nil) + require.Less(t, status, http.StatusBadRequest, path+": "+body) + } + + fresh := newAPIMStack(t) + require.NoError(t, fresh.handler.Restore(t.Context(), e.handler.Snapshot(t.Context()))) + + for _, path := range []string{ + "/certificates/pc", "/diagnostics/applicationinsights", "/schemas/gs", "/apis/echo/schemas/as", + "/products/starter/policies/policy", "/groups/guests", "/subscriptions/master", "/products/unlimited", + } { + status, body, _ = fresh.raw(t, http.MethodGet, fresh.armPath(path), "", nil) + assert.Equal(t, http.StatusOK, status, path+": "+body) + } + + status, body, _ = fresh.raw(t, http.MethodGet, fresh.armPath("/certificates/pc"), "", nil) + require.Equal(t, http.StatusOK, status) + assert.Contains(t, body, "CN=persist.example") +} + +func rsaCertPFX(t *testing.T, cn string) (*rsa.PrivateKey, []byte, []byte) { + t.Helper() + + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + tpl := &x509.Certificate{ + SerialNumber: big.NewInt(9), Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + pfx, err := pkcs12.Modern.Encode(key, cert, nil, "pw") + require.NoError(t, err) + + return key, der, pfx +} + +func TestAPIMGateway_AuthenticationCertificate(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + _, der, pfx := rsaCertPFX(t, "client.example") + sum := sha1.Sum(der) + thumb := strings.ToUpper(hex.EncodeToString(sum[:])) + + cn := make(chan string, 4) + be := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + name := "none" + if len(r.TLS.PeerCertificates) > 0 { + name = r.TLS.PeerCertificates[0].Subject.CommonName + } + + cn <- name + + _, _ = io.WriteString(w, "secure") + })) + be.TLS = &tls.Config{ClientAuth: tls.RequestClientCert, MinVersion: tls.VersionTLS12} + be.StartTLS() + t.Cleanup(be.Close) + + pool := x509.NewCertPool() + pool.AddCert(be.Certificate()) + e.prov.SetBackendRootCAs(pool) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/certificates/cl"), + `{"properties":{"data":"`+base64.StdEncoding.EncodeToString(pfx)+`","password":"pw"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + e.putAPI(t, "sec", "sec", be.URL) + e.putOp(t, "sec", "g", "get", "/x") + + tests := []struct { + name, attrs, wantCN string + }{ + {"thumbprint", `thumbprint="` + thumb + `"`, "client.example"}, + {"certificate-id", `certificate-id="cl"`, "client.example"}, + {"no policy", "", "none"}, + } + + for _, tc := range tests { + stmt := "" + if tc.attrs != "" { + stmt = `` + } + + pb, err := json.Marshal( + map[string]any{"properties": map[string]any{"format": "xml", "value": policyDoc(stmt, "", "")}}, + jsonx.V1(), + ) + require.NoError(t, err) + + status, body, _ = e.raw(t, http.MethodPut, e.armPath("/apis/sec/policies/policy"), string(pb), nil) + require.Less(t, status, http.StatusBadRequest, tc.name+body) + + status, body, _ = e.call(t, "GET", "/sec/x", "", nil) + require.Equal(t, http.StatusOK, status, tc.name+body) + assert.Equal(t, tc.wantCN, <-cn, tc.name) + } + + bads := []string{ + `thumbprint="DEADBEEF"`, + `certificate-id="ghost"`, + ``, + `thumbprint="` + thumb + `" certificate-id="cl"`, + } + + for _, bad := range bads { + resp := e.policy( + t, + "/apis/sec", + policyDoc(``, "", ""), + http.StatusBadRequest, + ) + assert.Contains(t, resp, "ValidationError") + } +} + +func TestAPIMGateway_ValidateJWTCertificate(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + key, der, _ := rsaCertPFX(t, "signer") + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/certificates/signer"), + `{"properties":{"data":"`+base64.StdEncoding.EncodeToString(der)+`"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + e.policy( + t, + "/apis/echo", + jwtPolicy( + ``+ + ``, + ), + http.StatusCreated, + ) + + tok, err := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"exp": e.clock.Now().Add(time.Hour).Unix()}). + SignedString(key) + require.NoError(t, err) + + status, body, _ = e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": tok}) + assert.Equal(t, http.StatusOK, status, body) + + other, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + bad, err := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{"exp": e.clock.Now().Add(time.Hour).Unix()}). + SignedString(other) + require.NoError(t, err) + + status, _, _ = e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": bad}) + assert.Equal(t, http.StatusUnauthorized, status) + + resp := e.policy( + t, + "/apis/echo", + jwtPolicy( + ``+ + ``, + ), + http.StatusBadRequest, + ) + assert.Contains(t, resp, "'ghost'") +} diff --git a/services/azurearm/apim_policy_test.go b/services/azurearm/apim_policy_test.go index c8ed9736ef..51bdee7c07 100644 --- a/services/azurearm/apim_policy_test.go +++ b/services/azurearm/apim_policy_test.go @@ -50,8 +50,8 @@ func TestAPIMPolicy_Validation(t *testing.T) { {name: "two roots", doc: "", wantErr: "single root"}, {name: "unknown section", doc: "", wantErr: "'sideways'"}, { - name: "unsupported policy", doc: policyDoc(``, "", ""), - wantErr: "Error in element 'validate-jwt' on line 1", + name: "unsupported policy", doc: policyDoc(``, "", ""), + wantErr: "Error in element 'json-to-xml' on line 1", }, { name: "unsupported nested", @@ -75,9 +75,13 @@ func TestAPIMPolicy_Validation(t *testing.T) { wantErr: "exists-action", }, { - name: "expression attribute", - doc: policyDoc(`@(context.Request.Url)`, "", ""), - wantErr: "expressions", + name: "expression attribute", + doc: policyDoc( + `@(context.Request.Body.As())`, + "", + "", + ), + wantErr: "context.Request.Body", }, {name: "rate zero", doc: policyDoc(``, "", ""), wantErr: "'calls'"}, { diff --git a/services/azurearm/apim_review_cache_test.go b/services/azurearm/apim_review_cache_test.go new file mode 100644 index 0000000000..1d290c2657 --- /dev/null +++ b/services/azurearm/apim_review_cache_test.go @@ -0,0 +1,44 @@ +package azurearm_test + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAPIMGateway_CacheStoreDropsPerClientHeaders(t *testing.T) { + t.Parallel() + + var hits atomic.Int64 + + be := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.Header().Set("Set-Cookie", "session=abc; HttpOnly") + w.Header().Set("Proxy-Authenticate", "Basic") + w.Header().Set("X-Shared", "yes") + _, _ = w.Write([]byte("body")) + })) + t.Cleanup(be.Close) + + e := newGWEnv(t) + e.putAPI(t, "data", "data", be.URL) + e.putOp(t, "data", "get", "get", "/{id}") + e.policy(t, "/apis/data", ` + `, http.StatusCreated) + + _, _, first := e.call(t, "GET", "/data/a", "", nil) + assert.Equal(t, "session=abc; HttpOnly", first.Get("Set-Cookie"), "the first client gets its own cookie") + + status, body, second := e.call(t, "GET", "/data/a", "", nil) + require.Equal(t, http.StatusOK, status) + assert.Equal(t, "body", body) + assert.Equal(t, int64(1), hits.Load(), "the second call was served from the cache") + assert.Equal(t, "yes", second.Get("X-Shared")) + assert.Empty(t, second.Values("Set-Cookie"), "a cached response never replays another client's cookie") + assert.Empty(t, second.Values("Proxy-Authenticate")) +} diff --git a/services/azurearm/apim_review_internal_test.go b/services/azurearm/apim_review_internal_test.go new file mode 100644 index 0000000000..898d133e0c --- /dev/null +++ b/services/azurearm/apim_review_internal_test.go @@ -0,0 +1,98 @@ +package azurearm + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "math/big" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "software.sslmate.com/src/go-pkcs12" +) + +func apimTestPFX(t *testing.T, cn string) string { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + tpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + } + der, err := x509.CreateCertificate(rand.Reader, tpl, tpl, &key.PublicKey, key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + pfx, err := pkcs12.Modern.Encode(key, cert, nil, "pw") + require.NoError(t, err) + + return base64.StdEncoding.EncodeToString(pfx) +} + +func TestAPIMAuthCertificate_ExpressionBodyKeysOnValue(t *testing.T) { + t.Parallel() + + p := NewAPIMProvider() + node := &polNode{Attrs: map[string]string{ + apimCBodyAttr: `@((string)context.Variables["pfx"])`, apimCPasswordAttr: "pw", + }} + + clientFor := func(pfx string) *gwState { + g := &gwState{ + p: p, plan: &gwPlan{svcKey: "svc", now: time.Now}, vars: map[string]any{"pfx": pfx}, + } + g.authCert(node) + require.False(t, g.errored) + require.NotNil(t, g.client) + + return g + } + + a, b := clientFor(apimTestPFX(t, "tenant-a")), clientFor(apimTestPFX(t, "tenant-b")) + assert.NotSame(t, a.client, b.client, "different certificates must not share a client") +} + +func TestAPIMRestore_AddsMissingSystemEntities(t *testing.T) { + t.Parallel() + + now := time.Now() + src := NewAPIMProvider() + s := newAPIMService("sub", "rg", "old", now) + s.Generic = map[string]map[string]*apimEntity{apimGroupsType: { + entKey("", "guests"): {ID: "guests", Props: map[string]any{apimCDisplayName: "mine", fieldType: "custom"}}, + }} + delete(s.Subs, entKey("", apimMasterSub)) + + key := apimKey("sub", "rg", "old") + src.svcs[key] = s + + dst := NewAPIMProvider() + dst.restore(src.snapshot()) + + got := dst.svcs[key] + require.NotNil(t, got) + + for _, id := range []string{"administrators", "developers"} { + assert.NotNil(t, got.Generic[apimGroupsType][entKey("", id)], id) + } + + assert.Equal(t, "custom", strOf(got.Generic[apimGroupsType][entKey("", "guests")].Props, fieldType), + "a user-created group is not overwritten") + + master := got.Subs[entKey("", apimMasterSub)] + require.NotNil(t, master) + + dst2 := NewAPIMProvider() + dst2.restore(dst.snapshot()) + assert.Equal(t, master.Props[redisPropPrimaryKey], + dst2.svcs[key].Subs[entKey("", apimMasterSub)].Props[redisPropPrimaryKey], "restore is idempotent") +} diff --git a/services/azurearm/apim_review_jwt_test.go b/services/azurearm/apim_review_jwt_test.go new file mode 100644 index 0000000000..e25f18e2fa --- /dev/null +++ b/services/azurearm/apim_review_jwt_test.go @@ -0,0 +1,102 @@ +package azurearm_test + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAPIMGateway_ValidateJWTEmptyClaimMatches(t *testing.T) { + t.Parallel() + + secret := []byte("0123456789abcdef0123456789abcdef") + key := base64.StdEncoding.EncodeToString(secret) + + tests := []struct { + claims jwt.MapClaims + name string + policy string + }{ + {jwt.MapClaims{}, "missing aud, empty audience", ``}, + {jwt.MapClaims{}, "missing iss, empty issuer", ``}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", jwtPolicy(``+signingKey(key)+tt.policy+ + ``), http.StatusCreated) + + tt.claims["exp"] = e.clock.Now().Add(time.Hour).Unix() + tok := signHS(t, jwt.SigningMethodHS256, secret, tt.claims) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": tok}) + assert.Equal(t, http.StatusUnauthorized, status, body) + }) + } +} + +func TestAPIMGateway_ValidateJWTMalformedHidesParserText(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + key := base64.StdEncoding.EncodeToString([]byte("0123456789abcdef")) + e.policy(t, "/apis/echo", jwtPolicy(``+signingKey(key)+``), + http.StatusCreated) + + tests := []struct{ name, tok string }{ + {"two segments", "a.b"}, + {"bad base64", "!!!.@@@.###"}, + {"non json header", "aGVsbG8.aGVsbG8.c2ln"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": tt.tok}) + assert.Equal(t, http.StatusUnauthorized, status, body) + assert.NotContains(t, body, "illegal base64") + assert.NotContains(t, body, "invalid character") + assert.NotContains(t, body, "token is malformed") + }) + } +} + +func TestAPIMGateway_ValidateJWTFailedConfigFetchIsCached(t *testing.T) { + t.Parallel() + + var hits atomic.Int64 + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + hits.Add(1) + w.WriteHeader(http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + + e := newGWEnv(t) + e.policy(t, "/apis/echo", jwtPolicy(``), http.StatusCreated) + + for range 5 { + status, _, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": "a.b.c"}) + require.Equal(t, http.StatusUnauthorized, status) + } + + assert.Equal(t, int64(1), hits.Load(), "a failing configuration endpoint is not refetched per request") + + e.clock.Advance(6 * time.Minute) + + status, _, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-T": "a.b.c"}) + require.Equal(t, http.StatusUnauthorized, status) + assert.Equal(t, int64(2), hits.Load(), "the retry interval elapsed") +} diff --git a/services/azurearm/apim_review_throttle_test.go b/services/azurearm/apim_review_throttle_test.go new file mode 100644 index 0000000000..359d8a378d --- /dev/null +++ b/services/azurearm/apim_review_throttle_test.go @@ -0,0 +1,80 @@ +package azurearm_test + +import ( + "net/http" + "sync" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func (e *gwEnv) parallelStatuses(t *testing.T, n int) map[int]int { + t.Helper() + + var ( + mu sync.Mutex + wg sync.WaitGroup + bad atomic.Int64 + out = map[int]int{} + ) + + for range n { + wg.Go(func() { + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, + e.url+"/_apim/"+apimSvc+"/echo/items/1", nil) + if err != nil { + bad.Add(1) + + return + } + + req.Header.Set("Ocp-Apim-Subscription-Key", e.key) + + resp, err := e.hc.Do(req) + if err != nil { + bad.Add(1) + + return + } + + _ = resp.Body.Close() + + mu.Lock() + out[resp.StatusCode]++ + mu.Unlock() + }) + } + + wg.Wait() + require.Zero(t, bad.Load()) + + return out +} + +func TestAPIMGateway_CountersUnderConcurrency(t *testing.T) { + t.Parallel() + + tests := []struct { + name, policy string + denied int + }{ + {"rate limit by key", ``, 429}, + {"rate limit", ``, 429}, + {"quota by key", ``, 403}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(tt.policy, "", ""), http.StatusCreated) + + got := e.parallelStatuses(t, 60) + assert.Equal(t, 10, got[http.StatusOK], "%v", got) + assert.Equal(t, 50, got[tt.denied], "%v", got) + }) + } +} diff --git a/services/azurearm/apim_review_ws_test.go b/services/azurearm/apim_review_ws_test.go new file mode 100644 index 0000000000..90267e1570 --- /dev/null +++ b/services/azurearm/apim_review_ws_test.go @@ -0,0 +1,288 @@ +package azurearm_test + +import ( + "crypto/sha1" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "testing" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/azurearm" +) + +func TestAPIMGateway_WebSocketHopByHopHeaders(t *testing.T) { + t.Parallel() + + e, be := newWSEnv(t) + + c, resp, err := e.wsDial(t, "/ws", map[string]string{ + "X-Token": "secret", "Proxy-Authorization": "Basic cHJveHk6cHc=", "Keep-Alive": "timeout=5", + "Proxy-Connection": "keep-alive", "Te": "trailers", + }) + require.NoError(t, err) + + defer resp.Body.Close() + defer c.Close() + + h := <-be.seen + for _, name := range []string{"Proxy-Authorization", "Keep-Alive", "Proxy-Connection", "Te"} { + assert.Empty(t, h.Get(name), name) + } + + assert.Equal(t, "secret", h.Get("X-Token"), "end-to-end headers are kept") +} + +func TestAPIMGateway_WebSocketSlotsReleased(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + up := websocket.Upgrader{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + + defer c.Close() + + for { + if _, _, rerr := c.ReadMessage(); rerr != nil { + return + } + } + })) + t.Cleanup(srv.Close) + + e.wsAPI(t, "ws", `"https","wss"`, "ws"+strings.TrimPrefix(srv.URL, "http")) + + for i := range 300 { + c, resp, err := e.wsDial(t, "/ws", nil) + require.NoError(t, err, "session %d", i) + require.NoError(t, c.Close()) + require.NoError(t, resp.Body.Close()) + } +} + +func apimProviderOf(t *testing.T, e *gwEnv) *azurearm.APIMProvider { + t.Helper() + + pr, ok := e.handler.Registry.ProviderNamed("Microsoft.ApiManagement") + require.True(t, ok) + + prov, ok := pr.(*azurearm.APIMProvider) + require.True(t, ok) + + return prov +} + +func goroutinesIn(marker string) int { + buf := make([]byte, 1<<22) + buf = buf[:runtime.Stack(buf, true)] + + n := 0 + + for g := range strings.SplitSeq(string(buf), "\n\n") { + if strings.Contains(g, marker) { + n++ + } + } + + return n +} + +//nolint:paralleltest // inspects the process's goroutines, so it must not overlap other APIM tests +func TestAPIMGateway_CloseEndsWebSocketSessions(t *testing.T) { + e, be := newWSEnv(t) + secret := map[string]string{"X-Token": "secret"} + + clients := make([]*websocket.Conn, 0, 2) + + for range 2 { + c, resp, err := e.wsDial(t, "/ws", secret) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + + clients = append(clients, c) + } + + require.Equal(t, 2, goroutinesIn("(*gwState).proxyWebSocket")) + + apimProviderOf(t, e).Close() + + for _, c := range clients { + _, _, err := c.ReadMessage() + require.Error(t, err, "the client leg is closed") + _ = c.Close() + } + + <-be.closed + <-be.closed + + assert.Zero(t, goroutinesIn("(*gwState).proxyWebSocket"), "no session goroutine remains") + assert.Zero(t, goroutinesIn("handleUpgradeResponse")) + + _, resp, err := e.wsDial(t, "/ws", secret) + require.Error(t, err) + assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode, "a closed gateway refuses new sessions") +} + +//nolint:paralleltest // inspects the process's goroutines, so it must not overlap other APIM tests +func TestAPIMGateway_CloseCancelsOneWayRequests(t *testing.T) { + e := newGWEnv(t) + + started, ended := make(chan struct{}), make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + close(started) + <-r.Context().Done() + close(ended) + })) + t.Cleanup(srv.Close) + + e.policy(t, "/apis/echo", policyDoc(``+srv.URL+ + `/auditPUT`, "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", nil) + require.Equal(t, http.StatusOK, status, body) + + <-started + + apimProviderOf(t, e).Close() + + <-ended + + assert.Zero(t, goroutinesIn("(*gwState).sendOneWay")) +} + +type wsSeen struct { + header http.Header + cn string +} + +func newSeenWSBackend(t *testing.T, tlsCfg *tls.Config) (*httptest.Server, chan wsSeen) { + t.Helper() + + seen := make(chan wsSeen, 4) + up := websocket.Upgrader{} + + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s := wsSeen{header: r.Header.Clone()} + if r.TLS != nil && len(r.TLS.PeerCertificates) > 0 { + s.cn = r.TLS.PeerCertificates[0].Subject.CommonName + } + + seen <- s + + c, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + + defer c.Close() + + for { + if _, _, rerr := c.ReadMessage(); rerr != nil { + return + } + } + })) + + if tlsCfg != nil { + srv.TLS = tlsCfg + srv.StartTLS() + } else { + srv.Start() + } + + t.Cleanup(srv.Close) + + return srv, seen +} + +func TestAPIMGateway_WebSocketBackendAuthentication(t *testing.T) { + t.Parallel() + + t.Run("authentication-basic", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + srv, seen := newSeenWSBackend(t, nil) + e.wsAPI(t, "ws", `"https","wss"`, "ws"+strings.TrimPrefix(srv.URL, "http")) + e.policy(t, "/apis/ws", policyDoc(``, "", ""), + http.StatusCreated) + + c, resp, err := e.wsDial(t, "/ws", map[string]string{"Authorization": "Bearer client-token"}) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + require.NoError(t, c.Close()) + + got := (<-seen).header + assert.Equal(t, "Basic c3ZjOnB3", got.Get("Authorization"), "the policy credentials replace the client's") + }) + + t.Run("backend credentials", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + srv, seen := newSeenWSBackend(t, nil) + e.wsAPI(t, "ws", `"https","wss"`, "ws"+strings.TrimPrefix(srv.URL, "http")) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/backends/bk"), + `{"properties":{"url":"`+srv.URL+`","protocol":"http","credentials":{"header":{"X-Cred":["v1"]},`+ + `"authorization":{"scheme":"Bearer","parameter":"tok"}}}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + e.policy(t, "/apis/ws", policyDoc(``, "", ""), http.StatusCreated) + + c, resp, err := e.wsDial(t, "/ws", nil) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + require.NoError(t, c.Close()) + + got := (<-seen).header + assert.Equal(t, "v1", got.Get("X-Cred")) + assert.Equal(t, "Bearer tok", got.Get("Authorization")) + }) + + t.Run("authentication-certificate", func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + _, der, pfx := rsaCertPFX(t, "ws-client.example") + sum := sha1.Sum(der) + thumb := strings.ToUpper(hex.EncodeToString(sum[:])) + + srv, seen := newSeenWSBackend( + t, + &tls.Config{ClientAuth: tls.RequireAnyClientCert, MinVersion: tls.VersionTLS12}, + ) + + pool := x509.NewCertPool() + pool.AddCert(srv.Certificate()) + e.prov.SetBackendRootCAs(pool) + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/certificates/cl"), + `{"properties":{"data":"`+base64.StdEncoding.EncodeToString(pfx)+`","password":"pw"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + e.wsAPI(t, "ws", `"https","wss"`, "wss"+strings.TrimPrefix(srv.URL, "https")) + e.policy(t, "/apis/ws", policyDoc(``, "", ""), + http.StatusCreated) + + c, resp, err := e.wsDial(t, "/ws", nil) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + require.NoError(t, c.Close()) + + assert.Equal(t, "ws-client.example", (<-seen).cn) + }) +} diff --git a/services/azurearm/apim_send_test.go b/services/azurearm/apim_send_test.go new file mode 100644 index 0000000000..e3e9c9a804 --- /dev/null +++ b/services/azurearm/apim_send_test.go @@ -0,0 +1,224 @@ +package azurearm_test + +import ( + "encoding/base64" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type recordedReq struct { + header http.Header + method string + path string + body string +} + +func newRecordingBackend(t *testing.T, reply string) (*httptest.Server, chan recordedReq) { + t.Helper() + + ch := make(chan recordedReq, 16) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + ch <- recordedReq{header: r.Header.Clone(), method: r.Method, path: r.URL.Path, body: string(b)} + + w.Header().Set("X-Reply", "yes") + _, _ = io.WriteString(w, reply) + })) + t.Cleanup(srv.Close) + + return srv, ch +} + +func TestAPIMGateway_SendRequest(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + aux, got := newRecordingBackend(t, "token-ok") + + e.policy(t, "/apis/echo", policyDoc(` + + @("`+aux.URL+`/introspect/" + context.Request.MatchedParameters["id"]) + POST + + @("t-" + context.Request.Headers.GetValueOrDefault("X-In", "")) + + + @("token=" + context.Request.Headers.GetValueOrDefault("X-In", "")) + + `+ + headerPolicy("X-Status", `@(((IResponse)context.Variables["r"]).StatusCode)`)+ + headerPolicy("X-Body", `@(((IResponse)context.Variables["r"]).Body.As())`)+ + headerPolicy("X-Reply", `@(((IResponse)context.Variables["r"]).Headers.GetValueOrDefault("X-Reply", "no"))`), + "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/42", "", map[string]string{"X-In": "abc"}) + require.Equal(t, http.StatusOK, status, body) + + r := <-got + assert.Equal(t, "POST", r.method) + assert.Equal(t, "/introspect/42", r.path) + assert.Equal(t, "t-abc", r.header.Get("X-Token")) + assert.Equal(t, "token=abc", r.body) + + h := decodeEcho(t, body).Header + assert.Equal(t, []string{"200"}, h["X-Status"]) + assert.Equal(t, []string{"token-ok"}, h["X-Body"]) + assert.Equal(t, []string{"yes"}, h["X-Reply"]) +} + +func TestAPIMGateway_SendRequestCopy(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + aux, got := newRecordingBackend(t, "ok") + + e.policy(t, "/apis/echo", policyDoc(` + `+aux.URL+`/mirror`, + "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "POST", "/echo/items", "payload", map[string]string{"X-Copy": "1"}) + require.Equal(t, http.StatusOK, status, body) + + r := <-got + assert.Equal(t, "POST", r.method) + assert.Equal(t, "/mirror", r.path) + assert.Equal(t, "1", r.header.Get("X-Copy")) + assert.Equal(t, "payload", r.body) + assert.Equal(t, "payload", decodeEcho(t, body).Body, "the original request still reaches its backend with its body") +} + +func TestAPIMGateway_SendOneWayRequest(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + aux, got := newRecordingBackend(t, "ignored") + + e.policy(t, "/apis/echo", policyDoc(` + `+aux.URL+`/auditPUT + yes + @(context.Request.Method)`, "", ""), http.StatusCreated) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", nil) + require.Equal(t, http.StatusOK, status, body) + + r := <-got + assert.Equal(t, "PUT", r.method) + assert.Equal(t, "/audit", r.path) + assert.Equal(t, "yes", r.header.Get("X-Audit")) + assert.Equal(t, "GET", r.body) +} + +func TestAPIMGateway_SendRequestErrors(t *testing.T) { + t.Parallel() + + tests := []struct { //nolint:govet // test-only struct; layout not performance-critical + name string + ignore string + wantStatus int + wantHeader string + }{ + {"ignore-error true", "true", http.StatusOK, "True"}, + {"ignore-error false", "false", http.StatusBadGateway, ""}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", ` + + http://203.0.113.9:81/xGET`+ + headerPolicy("X-Null", `@(context.Variables.GetValueOrDefault("r") == null)`)+` + + + @(context.LastError.Source) + `, http.StatusCreated) + + status, body, hdr := e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, tc.wantStatus, status, body) + + if tc.ignore == "true" { + assert.Equal(t, []string{tc.wantHeader}, decodeEcho(t, body).Header["X-Null"]) + + return + } + + assert.Equal(t, "send-request", hdr.Get("X-Source")) + }) + } +} + +func TestAPIMGateway_AuthenticationBasic(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy( + t, + "/apis/echo", + policyDoc(``, "", ""), + http.StatusCreated, + ) + + status, body, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"Authorization": "Bearer client"}) + require.Equal(t, http.StatusOK, status, body) + + want := "Basic " + base64.StdEncoding.EncodeToString([]byte("svc:p@ss")) + assert.Equal(t, []string{want}, decodeEcho(t, body).Header["Authorization"]) +} + +func TestAPIMSend_Validation(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + + tests := []struct{ name, stmt, want string }{ + { + "no url", + `GET`, + "element is required unless mode is copy", + }, + { + "no method", + `http://a/`, + "element is required unless mode is copy", + }, + { + "bad url", + `ftp://a/GET`, + "absolute http or https", + }, + { + "bad method", + `http://a/FETCH`, + "set-method", + }, + { + "no variable", + `http://a/GET`, + "'response-variable-name' is required", + }, + {"bad mode", ``, "'mode'"}, + {"basic without password", ``, "'password' is required"}, + {"basic in outbound", "", "not allowed in the outbound"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + doc := policyDoc(tc.stmt, "", "") + if tc.stmt == "" { + doc = policyDoc("", "", ``) + } + + body := e.policy(t, "/apis/echo", doc, http.StatusBadRequest) + assert.Contains(t, body, tc.want) + }) + } +} diff --git a/services/azurearm/apim_sources_test.go b/services/azurearm/apim_sources_test.go index 3521036735..5255e3d7fd 100644 --- a/services/azurearm/apim_sources_test.go +++ b/services/azurearm/apim_sources_test.go @@ -551,8 +551,8 @@ func TestAPIMPolicy_ReferenceRules(t *testing.T) { { name: "statement in on-error", scope: "/apis/echo", doc: "" + - `y`, - wantErr: "on-error", + ``, + wantErr: "not allowed in the on-error", }, { name: "cors without origins", scope: "/apis/echo", diff --git a/services/azurearm/apim_throttle_test.go b/services/azurearm/apim_throttle_test.go new file mode 100644 index 0000000000..d5f4565667 --- /dev/null +++ b/services/azurearm/apim_throttle_test.go @@ -0,0 +1,193 @@ +package azurearm_test + +import ( + "net/http" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAPIMGateway_RateLimitByKey(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(``, "", ""), http.StatusCreated) + + call := func(user string) (int, http.Header) { + status, _, hdr := e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-User": user}) + + return status, hdr + } + + status, hdr := call("alice") + assert.Equal(t, 200, status) + assert.Equal(t, "1", hdr.Get("X-Left")) + assert.Equal(t, "2", hdr.Get("X-Total")) + + call("alice") + e.clock.Advance(20 * time.Second) + + status, hdr = call("alice") + assert.Equal(t, http.StatusTooManyRequests, status) + assert.Equal(t, "40", hdr.Get("X-Retry")) + + status, _ = call("bob") + assert.Equal(t, 200, status, "counters are per key") + + e.clock.Advance(41 * time.Second) + + status, _ = call("alice") + assert.Equal(t, 200, status, "window renewed") +} + +func TestAPIMGateway_RateLimitByKeyPostponedIncrement(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(``, "", ""), http.StatusCreated) + + status, _, _ := e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, 200, status) + + status, _, _ = e.call(t, "GET", "/echo/items/1", "", nil) + assert.Equal(t, http.StatusTooManyRequests, status) +} + +func TestAPIMGateway_QuotaByKey(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(``, "", ""), http.StatusCreated) + + call := func(user, count string) (int, string, http.Header) { + return e.call(t, "GET", "/echo/items/1", "", map[string]string{"X-User": user, "X-Count": count}) + } + + for range 3 { + status, _, _ := call("u", "0") + require.Equal(t, 200, status, "uncounted calls never exhaust the quota") + } + + call("u", "1") + call("u", "1") + + e.clock.Advance(30 * time.Minute) + + status, body, hdr := call("u", "1") + assert.Equal(t, http.StatusForbidden, status) + assert.Contains(t, body, "Out of call volume quota. Quota will be replenished in 00:") + assert.NotEmpty(t, hdr.Get("Retry-After")) + + status, _, _ = call("other", "1") + assert.Equal(t, 200, status) + + e.clock.Advance(time.Hour) + + status, _, _ = call("u", "1") + assert.Equal(t, 200, status, "the fixed window renewed") +} + +func TestAPIMGateway_QuotaByKeyBandwidth(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.policy(t, "/apis/echo", policyDoc(``, "", ""), + http.StatusCreated) + + status, _, _ := e.call(t, "POST", "/echo/items", strings.Repeat("x", 2048), nil) + require.Equal(t, 200, status) + + status, body, hdr := e.call(t, "POST", "/echo/items", "x", nil) + assert.Equal(t, http.StatusForbidden, status) + assert.Contains(t, body, `"message":"Out of bandwidth quota."`) + assert.Empty(t, hdr.Get("Retry-After"), "an infinite period has no renewal") +} + +func TestAPIMGateway_QuotaProductScope(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putProduct(t, "gold", true) + e.linkProductAPI(t, "gold", "echo") + k1 := e.productSubscription(t, "s1", "gold") + k2 := e.productSubscription(t, "s2", "gold") + + e.policy(t, "/products/gold", policyDoc(` + `, "", ""), http.StatusCreated) + + status, _, _ := e.call(t, "GET", "/echo/items/1", "", map[string]string{"Ocp-Apim-Subscription-Key": k1}) + require.Equal(t, 200, status) + + status, body, hdr := e.call(t, "GET", "/echo/items/1", "", map[string]string{"Ocp-Apim-Subscription-Key": k1}) + assert.Equal(t, http.StatusForbidden, status, "the nested api quota of 1 call applies independently") + assert.Contains(t, body, "Out of call volume quota. Quota will be replenished in 0") + assert.NotEmpty(t, hdr.Get("Retry-After")) + + status, _, _ = e.call(t, "GET", "/echo/items/1", "", map[string]string{"Ocp-Apim-Subscription-Key": k2}) + assert.Equal(t, 200, status, "quotas are per subscription") +} + +func TestAPIMThrottle_Validation(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + e.putProduct(t, "gold", true) + + tests := []struct { + name, scope, stmt, want string + }{ + {"quota at api scope", "/apis/echo", ``, "product scope only"}, + {"quota no limit", "/products/gold", ``, "Either 'calls' or 'bandwidth'"}, + {"quota no period", "/products/gold", ``, "'renewal-period' is required"}, + { + "quota-by-key short period", + "/apis/echo", + ``, + "'renewal-period'", + }, + { + "quota-by-key no key", + "/apis/echo", + ``, + "'counter-key' is required", + }, + { + "rlbk long period", + "/apis/echo", + ``, + "'renewal-period'", + }, + { + "rlbk bad expression", + "/apis/echo", + ``, + "'nope'", + }, + { + "quota api no id", + "/products/gold", + ``, + "'name' or 'id'", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + body := e.policy(t, tc.scope, policyDoc(tc.stmt, "", ""), http.StatusBadRequest) + assert.Contains(t, body, tc.want) + }) + } +} diff --git a/services/azurearm/apim_ws_test.go b/services/azurearm/apim_ws_test.go new file mode 100644 index 0000000000..0ecd76b512 --- /dev/null +++ b/services/azurearm/apim_ws_test.go @@ -0,0 +1,205 @@ +package azurearm_test + +import ( + "crypto/tls" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" + + "github.com/gorilla/websocket" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type wsBackend struct { + srv *httptest.Server + seen chan http.Header + paths chan string + closed chan struct{} + kick chan struct{} + once sync.Once +} + +func (b *wsBackend) kickNow() { b.once.Do(func() { close(b.kick) }) } + +func newWSBackend(t *testing.T) *wsBackend { + t.Helper() + + b := &wsBackend{ + seen: make(chan http.Header, 8), paths: make(chan string, 8), + closed: make(chan struct{}, 8), kick: make(chan struct{}), + } + + up := websocket.Upgrader{} + b.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b.seen <- r.Header.Clone() + b.paths <- r.URL.Path + + c, err := up.Upgrade(w, r, nil) + if err != nil { + return + } + + defer c.Close() + + go func() { + <-b.kick + _ = c.WriteControl( + websocket.CloseMessage, + websocket.FormatCloseMessage(websocket.CloseGoingAway, "bye"), + time.Now().Add(time.Second), + ) + _ = c.Close() + }() + + for { + mt, msg, rerr := c.ReadMessage() + if rerr != nil { + b.closed <- struct{}{} + + return + } + + _ = c.WriteMessage(mt, append([]byte("echo:"), msg...)) + } + })) + t.Cleanup(func() { + b.kickNow() + b.srv.Close() + }) + + return b +} + +func (e *gwEnv) wsAPI(t *testing.T, id, protocols, serviceURL string) { + t.Helper() + + status, body, _ := e.raw(t, http.MethodPut, e.armPath("/apis/"+id), + `{"properties":{"displayName":"`+id+`","path":"`+id+`","protocols":[`+protocols+`],"serviceUrl":"`+serviceURL+ + `","type":"websocket"}}`, nil) + require.Less(t, status, http.StatusBadRequest, body) + + e.putOp(t, id, "onhandshake", "get", "/") +} + +func (e *gwEnv) wsDial(t *testing.T, path string, hdr map[string]string) (*websocket.Conn, *http.Response, error) { + t.Helper() + + tr, ok := e.hc.Transport.(*http.Transport) + require.True(t, ok) + + h := http.Header{"Ocp-Apim-Subscription-Key": {e.key}} + for k, v := range hdr { + h.Set(k, v) + } + + d := websocket.Dialer{TLSClientConfig: tr.TLSClientConfig.Clone()} + d.TLSClientConfig.MinVersion = tls.VersionTLS12 + + return d.DialContext( + t.Context(), + "wss://"+strings.TrimPrefix(e.url, "https://")+"/_apim/"+apimSvc+path, + h, + ) +} + +func newWSEnv(t *testing.T) (*gwEnv, *wsBackend) { + t.Helper() + + e := newGWEnv(t) + be := newWSBackend(t) + e.wsAPI(t, "ws", `"https","wss"`, "ws"+strings.TrimPrefix(be.srv.URL, "http")+"/chat") + + e.policy(t, "/apis/ws", policyDoc(headerPolicy("X-Policy", "applied")+ + checkHeader("X-Token", "401", "token required", "false", "secret"), "", ""), http.StatusCreated) + + return e, be +} + +func TestAPIMGateway_WebSocket(t *testing.T) { + t.Parallel() + + secret := map[string]string{"X-Token": "secret"} + + t.Run("handshake rejected by the inbound policy", func(t *testing.T) { + t.Parallel() + + e, be := newWSEnv(t) + + _, resp, err := e.wsDial(t, "/ws", nil) + require.ErrorIs(t, err, websocket.ErrBadHandshake) + assert.Equal(t, http.StatusUnauthorized, resp.StatusCode) + assert.Empty(t, be.seen, "the backend never saw the handshake") + }) + + t.Run("frames pass both ways", func(t *testing.T) { + t.Parallel() + + e, be := newWSEnv(t) + + c, resp, err := e.wsDial(t, "/ws", secret) + require.NoError(t, err) + + defer resp.Body.Close() + + assert.Equal(t, http.StatusSwitchingProtocols, resp.StatusCode) + + require.NoError(t, c.WriteMessage(websocket.TextMessage, []byte("hello"))) + + _, msg, err := c.ReadMessage() + require.NoError(t, err) + assert.Equal(t, "echo:hello", string(msg)) + + h := <-be.seen + assert.Equal(t, "applied", h.Get("X-Policy"), "the handshake policies ran") + assert.Equal(t, "/chat/", <-be.paths) + + require.NoError(t, c.Close()) + <-be.closed + }) + + t.Run("backend close ends the client", func(t *testing.T) { + t.Parallel() + + e, be := newWSEnv(t) + + c, resp, err := e.wsDial(t, "/ws", secret) + require.NoError(t, err) + + defer resp.Body.Close() + + <-be.seen + <-be.paths + + be.kickNow() + + _, _, err = c.ReadMessage() + require.Error(t, err) + assert.True(t, websocket.IsCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure), "%v", err) + }) + + t.Run("plain request", func(t *testing.T) { + t.Parallel() + + e, _ := newWSEnv(t) + + status, body, _ := e.call(t, "GET", "/ws", "", secret) + assert.Equal(t, http.StatusInternalServerError, status) + assert.Contains(t, body, "not a WebSocket upgrade") + }) +} + +func TestAPIMGateway_WebSocketProtocols(t *testing.T) { + t.Parallel() + + e := newGWEnv(t) + be := newWSBackend(t) + e.wsAPI(t, "wsonly", `"ws"`, "ws"+strings.TrimPrefix(be.srv.URL, "http")) + + _, resp, err := e.wsDial(t, "/wsonly", nil) + require.Error(t, err) + assert.Equal(t, http.StatusNotFound, resp.StatusCode, "the API does not offer wss") +} diff --git a/services/azurearm/errors_logic.go b/services/azurearm/errors_logic.go index 34579f4d61..e4de10711a 100644 --- a/services/azurearm/errors_logic.go +++ b/services/azurearm/errors_logic.go @@ -15,6 +15,8 @@ var ( ErrLogicRepNotFound = errors.New("azurearm: logic run action repetition not found") ErrLogicHistoryNotFound = errors.New("azurearm: logic trigger history not found") ErrLogicVersionNotFound = errors.New("azurearm: logic workflow version not found") + ErrLogicRequestNotFound = errors.New("azurearm: logic request history not found") + ErrLogicOperationMissing = errors.New("azurearm: logic run operation not found") ErrLogicExpr = errors.New("logic expression error") ) @@ -59,6 +61,8 @@ func logicErrorDetails(err error) (errorEntry, bool) { {ErrLogicRepNotFound, notFoundEntry("The workflow run action repetition was not found.")}, {ErrLogicHistoryNotFound, notFoundEntry("The workflow trigger history was not found.")}, {ErrLogicVersionNotFound, notFoundEntry("The workflow version was not found.")}, + {ErrLogicRequestNotFound, notFoundEntry("The workflow run action request history was not found.")}, + {ErrLogicOperationMissing, notFoundEntry("The workflow run operation was not found.")}, } for _, e := range table { diff --git a/services/azurearm/logic_history_surface_test.go b/services/azurearm/logic_history_surface_test.go new file mode 100644 index 0000000000..1c7d82fb97 --- /dev/null +++ b/services/azurearm/logic_history_surface_test.go @@ -0,0 +1,541 @@ +package azurearm_test + +import ( + "context" + "encoding/json/v2" + "maps" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +func (s *logicStack) latestRunName(t *testing.T, wf string) string { + t.Helper() + + return *s.latestRun(t, wf).Name +} + +func (s *logicStack) requestHistories(t *testing.T, wf, action string) []*armlogic.RequestHistory { + t.Helper() + + var out []*armlogic.RequestHistory + + pager := s.factory.NewWorkflowRunActionRequestHistoriesClient(). + NewListPager(logicRG, wf, s.latestRunName(t, wf), action, nil) + for pager.More() { + page, err := pager.NextPage(t.Context()) + require.NoError(t, err) + + out = append(out, page.Value...) + } + + return out +} + +func httpCall(uri string, extra la) la { + in := la{ + "method": "POST", "uri": uri, "headers": la{"X-Keep": "1"}, "body": la{"hello": "world"}, + "authentication": la{"type": "Raw", "value": "Bearer secret-token"}, + "retryPolicy": la{"type": "fixed", "count": 1, "interval": "PT1S"}, + } + call := la{"type": "Http", "runAfter": la{}, "inputs": in} + + maps.Copy(call, extra) + + return call +} + +func TestLogicRequestHistories(t *testing.T) { + t.Parallel() + + tests := []struct { + extra la + name string + statuses []int + wantHidden bool + wantBodyLnk bool + }{ + {name: "single call", statuses: []int{http.StatusOK}, wantBodyLnk: true}, + { + name: "retry records every attempt", + statuses: []int{http.StatusInternalServerError, http.StatusOK}, + wantBodyLnk: true, + }, + { + name: "secure inputs hide the request details", statuses: []int{http.StatusOK}, wantBodyLnk: true, + extra: la{"runtimeConfiguration": la{"secureData": la{"properties": []any{"inputs"}}}}, + wantHidden: true, + }, + { + name: "secure outputs hide the response body", statuses: []int{http.StatusOK}, + extra: la{"runtimeConfiguration": la{"secureData": la{"properties": []any{"outputs"}}}}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + + var ( + mu = make(chan struct{}, 1) + calls int + auth []string + ) + + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + mu <- struct{}{} + n := calls + calls++ + auth = append(auth, r.Header.Get("Authorization")) + <-mu + + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Backend", "yes") + w.WriteHeader(tc.statuses[min(n, len(tc.statuses)-1)]) + _, _ = w.Write([]byte(`{"ok":true}`)) + })) + t.Cleanup(backend.Close) + + s.create(t, "hist", logicDef(requestTrigger(nil), la{"Call": httpCall(backend.URL+"/x?q=1", tc.extra)})) + + code, _, _ := s.post(t, s.callback(t, "hist"), `{}`) + require.Equal(t, http.StatusAccepted, code) + + if len(tc.statuses) > 1 { + s.clock.waitTimer(t) + s.clock.Advance(time.Second) + } + + s.waitRuns(t) + + hs := s.requestHistories(t, "hist", "Call") + require.Len(t, hs, len(tc.statuses)) + + for i, h := range hs { + p := h.Properties + require.NotNil(t, p) + assert.Equal(t, "Microsoft.Logic/workflows/runs/actions/requestHistories", *h.Type) + assert.Equal(t, "POST", *p.Request.Method) + assert.Equal(t, int32(tc.statuses[i]), *p.Response.StatusCode) + assert.False(t, p.EndTime.Before(*p.StartTime)) + + if tc.wantHidden { + assert.Nil(t, p.Request.URI) + assert.Nil(t, p.Request.Headers) + } else { + assert.Equal(t, backend.URL+"/x?q=1", *p.Request.URI) + + hdr, ok := p.Request.Headers.(map[string]any) + require.True(t, ok) + assert.Equal(t, "1", hdr["X-Keep"]) + assert.Equal(t, "hist", hdr["X-Ms-Workflow-Name"]) + assert.NotContains(t, hdr, "Authorization", "credentials are never recorded") + } + + if tc.wantBodyLnk { + assert.JSONEq(t, `{"ok":true}`, toJSON(t, s.content(t, p.Response.BodyLink))) + assert.EqualValues(t, len(`{"ok":true}`), *p.Response.BodyLink.ContentSize) + } else { + assert.Nil(t, p.Response.BodyLink) + assert.Nil(t, p.Response.Headers) + } + } + + got, err := s.factory.NewWorkflowRunActionRequestHistoriesClient(). + Get(t.Context(), logicRG, "hist", s.latestRunName(t, "hist"), "Call", *hs[0].Name, nil) + require.NoError(t, err) + assert.Equal(t, *hs[0].ID, *got.ID) + + _, err = s.factory.NewWorkflowRunActionRequestHistoriesClient(). + Get(t.Context(), logicRG, "hist", s.latestRunName(t, "hist"), "Call", "missing", nil) + require.Error(t, err) + + assert.Equal(t, append([]string(nil), auth...), auth) + + for _, a := range auth { + assert.Equal(t, "Bearer secret-token", a, "the backend still receives the credential") + } + }) + } +} + +func TestLogicRequestHistoryNotFound(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "plain", logicDef(requestTrigger(nil), la{"Mark": compose("1", nil)})) + s.invoke(t, "plain", `{}`) + + run := s.latestRunName(t, "plain") + c := s.factory.NewWorkflowRunActionRequestHistoriesClient() + + tests := []struct { + name string + run string + action string + }{ + {name: "unknown run", run: "nope", action: "Mark"}, + {name: "unknown action", run: run, action: "Nope"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := c.NewListPager(logicRG, "plain", tc.run, tc.action, nil).NextPage(t.Context()) + require.Error(t, err) + }) + } + + page, err := c.NewListPager(logicRG, "plain", run, "Mark", nil).NextPage(t.Context()) + require.NoError(t, err) + assert.Empty(t, page.Value, "an action that made no HTTP call has no request histories") +} + +func TestLogicRepetitionRequestHistories(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(r.URL.Path)) + })) + t.Cleanup(backend.Close) + + s.create(t, "loop", logicDef(requestTrigger(nil), la{"Loop": la{ + "type": "Foreach", "foreach": []any{"a", "b"}, "operationOptions": "Sequential", "runAfter": la{}, + "actions": la{"Call": la{ + "type": "Http", "runAfter": la{}, + "inputs": la{"method": "GET", "uri": backend.URL + "/@{item()}", "retryPolicy": la{"type": "none"}}, + }}, + }})) + s.invoke(t, "loop", `{}`) + + run := s.latestRunName(t, "loop") + reps := s.factory.NewWorkflowRunActionRepetitionsClient().NewListPager(logicRG, "loop", run, "Call", nil) + rpage, err := reps.NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, rpage.Value, 2) + + rc := s.factory.NewWorkflowRunActionRepetitionsRequestHistoriesClient() + + for i, item := range []string{"a", "b"} { + page, lerr := rc.NewListPager(logicRG, "loop", run, "Call", *rpage.Value[i].Name, nil).NextPage(t.Context()) + require.NoError(t, lerr) + require.Len(t, page.Value, 1) + assert.Equal(t, backend.URL+"/"+item, *page.Value[0].Properties.Request.URI) + assert.Equal(t, "/"+item, s.content(t, page.Value[0].Properties.Response.BodyLink)) + + got, gerr := rc.Get(t.Context(), logicRG, "loop", run, "Call", *rpage.Value[i].Name, *page.Value[0].Name, nil) + require.NoError(t, gerr) + assert.Equal(t, *page.Value[0].ID, *got.ID) + } + + _, err = rc.NewListPager(logicRG, "loop", run, "Call", "999999", nil).NextPage(t.Context()) + require.Error(t, err) +} + +func TestLogicExpressionTraces(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + action la + wantPath string + wantText string + wantValue any + wantSubs []string + wantHidden bool + }{ + { + name: "function call with nested call", + action: compose("@concat('a', toUpper('b'))", nil), + wantPath: "inputs", wantText: "@concat('a', toUpper('b'))", wantValue: "aB", + wantSubs: []string{"'a'", "toUpper('b')"}, + }, + { + name: "property of an object input", + action: la{"type": "Compose", "runAfter": la{}, "inputs": la{"n": "@add(1, 2)"}}, + wantPath: "inputs.n", wantText: "@add(1, 2)", wantValue: float64(3), wantSubs: []string{"1", "2"}, + }, + { + name: "interpolation", + action: la{ + "type": "Compose", "runAfter": la{}, "inputs": "x@{string(5)}y", + }, + wantPath: "inputs", wantText: "x@{string(5)}y", wantValue: "x5y", wantSubs: []string{"string(5)"}, + }, + { + name: "secure inputs hide the values", + action: la{ + "type": "Compose", "runAfter": la{}, "inputs": "@concat('a', 'b')", + "runtimeConfiguration": la{"secureData": la{"properties": []any{"inputs"}}}, + }, + wantPath: "inputs", wantText: "@concat('a', 'b')", wantSubs: []string{"'a'", "'b'"}, wantHidden: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "trace", logicDef(requestTrigger(nil), la{"Act": tc.action})) + s.invoke(t, "trace", `{}`) + + res, err := s.factory.NewWorkflowRunActionsClient(). + NewListExpressionTracesPager(logicRG, "trace", s.latestRunName(t, "trace"), "Act", nil). + NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, res.Inputs, 1) + + root := res.Inputs[0] + assert.Equal(t, tc.wantPath, *root.Path) + assert.Equal(t, tc.wantText, *root.Text) + + subs := make([]string, 0, len(root.Subexpressions)) + for _, sub := range root.Subexpressions { + subs = append(subs, *sub.Text) + } + + assert.Equal(t, tc.wantSubs, subs) + + if tc.wantHidden { + assert.Nil(t, root.Value) + assert.Nil(t, root.Subexpressions[0].Value) + + return + } + + assert.Equal(t, tc.wantValue, root.Value) + }) + } +} + +func TestLogicExpressionTracesErrorAndBounds(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "bad", logicDef(requestTrigger(nil), la{ + "Boom": compose("@div(1, 0)", nil), + "Many": la{"type": "Compose", "runAfter": la{}, "inputs": manyExpressions(250)}, + })) + s.invoke(t, "bad", `{}`) + + c := s.factory.NewWorkflowRunActionsClient() + run := s.latestRunName(t, "bad") + + boom, err := c.NewListExpressionTracesPager(logicRG, "bad", run, "Boom", nil).NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, boom.Inputs, 1) + require.NotNil(t, boom.Inputs[0].Error) + assert.NotEmpty(t, *boom.Inputs[0].Error.Message) + + many, err := c.NewListExpressionTracesPager(logicRG, "bad", run, "Many", nil).NextPage(t.Context()) + require.NoError(t, err) + assert.Len(t, many.Inputs, 100, "traces are bounded per action") + + _, err = c.NewListExpressionTracesPager(logicRG, "bad", run, "Nope", nil).NextPage(t.Context()) + require.Error(t, err) +} + +func manyExpressions(n int) []any { + out := make([]any, n) + for i := range out { + out[i] = "@utcNow()" + } + + return out +} + +func TestLogicRepetitionExpressionTraces(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "reptrace", logicDef(requestTrigger(nil), la{"Loop": la{ + "type": "Foreach", "foreach": []any{"a", "b"}, "operationOptions": "Sequential", "runAfter": la{}, + "actions": la{"Echo": compose("@toUpper(item())", nil)}, + }})) + s.invoke(t, "reptrace", `{}`) + + run := s.latestRunName(t, "reptrace") + c := s.factory.NewWorkflowRunActionRepetitionsClient() + reps, err := c.NewListPager(logicRG, "reptrace", run, "Echo", nil).NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, reps.Value, 2) + + for i, want := range []string{"A", "B"} { + res, terr := c.NewListExpressionTracesPager(logicRG, "reptrace", run, "Echo", *reps.Value[i].Name, nil). + NextPage(t.Context()) + require.NoError(t, terr) + require.Len(t, res.Inputs, 1) + assert.Equal(t, want, res.Inputs[0].Value) + } +} + +func TestLogicRunOperations(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "ops", logicDef(la{"manual": la{"type": "Request", "kind": "Http"}}, + la{"Mark": compose("@triggerBody()?['n']", nil)})) + s.create(t, "other", logicDef(la{"manual": la{"type": "Request", "kind": "Http"}}, + la{"Mark": compose("1", nil)})) + + code, _, _ := s.post(t, s.callback(t, "ops"), `{"n":7}`) + require.Equal(t, http.StatusAccepted, code) + s.waitRuns(t) + + hc := s.factory.NewWorkflowTriggerHistoriesClient() + page, err := hc.NewListPager(logicRG, "ops", "manual", nil).NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + + ctx, resp := captureResponse(t.Context()) + _, err = hc.Resubmit(ctx, logicRG, "ops", "manual", *page.Value[0].Name, nil) + require.NoError(t, err) + s.waitRuns(t) + + loc := (*resp).Header.Get("Location") + require.NotEmpty(t, loc) + + opID := opIDFrom(loc) + run := s.latestRunName(t, "ops") + oc := s.factory.NewWorkflowRunOperationsClient() + + got, err := oc.Get(t.Context(), logicRG, "ops", run, opID, nil) + require.NoError(t, err) + assert.Equal(t, run, *got.Name) + assert.Equal(t, armlogic.WorkflowStatusSucceeded, *got.Properties.Status) + + tests := []struct { + name string + wf string + run string + op string + }{ + {name: "unknown operation", wf: "ops", run: run, op: "00000000-0000-0000-0000-000000000000"}, + {name: "operation of another run", wf: "ops", run: *page.Value[0].Name, op: opID}, + {name: "unknown run", wf: "ops", run: "nope", op: opID}, + {name: "unknown workflow", wf: "missing", run: run, op: opID}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, gerr := oc.Get(t.Context(), logicRG, tc.wf, tc.run, tc.op, nil) + require.Error(t, gerr) + }) + } +} + +func TestLogicCancelRecordsOperation(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "cancelme", logicDef(requestTrigger(nil), la{ + "Pause": la{"type": "Wait", "runAfter": la{}, "inputs": la{"interval": la{"count": 1, "unit": "Hour"}}}, + })) + + code, _, _ := s.post(t, s.callback(t, "cancelme"), `{}`) + require.Equal(t, http.StatusAccepted, code) + s.clock.waitTimer(t) + + run := s.latestRunName(t, "cancelme") + + ctx, resp := captureResponse(t.Context()) + _, err := s.factory.NewWorkflowRunsClient().Cancel(ctx, logicRG, "cancelme", run, nil) + require.NoError(t, err) + s.waitRuns(t) + + loc := (*resp).Header.Get("Location") + require.Contains(t, loc, "/runs/"+run+"/operations/") + + status, body := s.rawJSON(t, http.MethodGet, "/workflows/cancelme/runs/"+run+"/operations/"+opIDFrom(loc), "") + require.Equal(t, http.StatusOK, status) + props, _ := body["properties"].(map[string]any) + assert.Equal(t, "Cancelled", props["status"]) +} + +func captureResponse(ctx context.Context) (context.Context, **http.Response) { + var resp *http.Response + + return policy.WithCaptureResponse(ctx, &resp), &resp +} + +func opIDFrom(loc string) string { + _, after, _ := strings.Cut(loc, "/operations/") + id, _, _ := strings.Cut(after, "?") + + return id +} + +func toJSON(t *testing.T, v any) string { + t.Helper() + + b, err := json.Marshal(v, jsonx.V1()) + require.NoError(t, err) + + return string(b) +} + +func TestLogicHistorySurfacePersistence(t *testing.T) { + t.Parallel() + + a := newLogicStack(t) + + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte("pong")) + })) + t.Cleanup(backend.Close) + + a.create(t, "keep", logicDef(la{"manual": la{"type": "Request", "kind": "Http"}}, la{ + "Call": httpCall(backend.URL, nil), + "Mark": la{"type": "Compose", "runAfter": la{"Call": []any{"Succeeded"}}, "inputs": "@concat('x', 'y')"}, + })) + + code, _, _ := a.post(t, a.callback(t, "keep"), `{}`) + require.Equal(t, http.StatusAccepted, code) + a.waitRuns(t) + + hc := a.factory.NewWorkflowTriggerHistoriesClient() + page, err := hc.NewListPager(logicRG, "keep", "manual", nil).NextPage(t.Context()) + require.NoError(t, err) + + ctx, resp := captureResponse(t.Context()) + _, err = hc.Resubmit(ctx, logicRG, "keep", "manual", *page.Value[0].Name, nil) + require.NoError(t, err) + a.waitRuns(t) + + opID := opIDFrom((*resp).Header.Get("Location")) + run := a.latestRunName(t, "keep") + + b := newLogicStack(t) + require.NoError(t, b.handler.Restore(t.Context(), a.handler.Snapshot(t.Context()))) + + hs := b.requestHistories(t, "keep", "Call") + require.Len(t, hs, 1) + assert.Equal(t, "pong", b.content(t, hs[0].Properties.Response.BodyLink)) + + tr, err := b.factory.NewWorkflowRunActionsClient(). + NewListExpressionTracesPager(logicRG, "keep", run, "Mark", nil).NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, tr.Inputs, 1) + assert.Equal(t, "xy", tr.Inputs[0].Value) + + got, err := b.factory.NewWorkflowRunOperationsClient().Get(t.Context(), logicRG, "keep", run, opID, nil) + require.NoError(t, err) + assert.Equal(t, run, *got.Name) +} diff --git a/services/azurearm/logic_http_cert_test.go b/services/azurearm/logic_http_cert_test.go new file mode 100644 index 0000000000..b4ffb2eea6 --- /dev/null +++ b/services/azurearm/logic_http_cert_test.go @@ -0,0 +1,329 @@ +package azurearm_test + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "math/big" + "net" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic" + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + pkcs12 "software.sslmate.com/src/go-pkcs12" +) + +const certPassword = "pfx-pass-w0rd" + +type testCA struct { + cert *x509.Certificate + key *ecdsa.PrivateKey + pool *x509.CertPool +} + +func newTestCA(t *testing.T, name string) *testCA { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: name}, IsCA: true, BasicConstraintsValid: true, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + pool := x509.NewCertPool() + pool.AddCert(cert) + + return &testCA{cert: cert, key: key, pool: pool} +} + +func (ca *testCA) issue(t *testing.T, cn string, usage x509.ExtKeyUsage) (*x509.Certificate, *rsa.PrivateKey) { + t.Helper() + + key, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: cn}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{usage}, + IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &key.PublicKey, ca.key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + return cert, key +} + +func (ca *testCA) pfx(t *testing.T, cn string) (string, *x509.Certificate) { + t.Helper() + + cert, key := ca.issue(t, cn, x509.ExtKeyUsageClientAuth) + raw, err := pkcs12.Modern2023.Encode(key, cert, nil, certPassword) + require.NoError(t, err) + + return base64.StdEncoding.EncodeToString(raw), cert +} + +// mtlsBackend is a TLS server that requires a client certificate issued by clientCA. +func mtlsBackend(t *testing.T, serverCA, clientCA *testCA) *httptest.Server { + t.Helper() + + cert, key := serverCA.issue(t, "backend", x509.ExtKeyUsageServerAuth) + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(r.TLS.PeerCertificates[0].Subject.CommonName + "|" + tls.VersionName(r.TLS.Version))) + })) + srv.TLS = &tls.Config{ + Certificates: []tls.Certificate{{Certificate: [][]byte{cert.Raw}, PrivateKey: key}}, + ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientCA.pool, MinVersion: tls.VersionTLS12, + } + srv.StartTLS() + t.Cleanup(srv.Close) + + return srv +} + +func TestLogicHTTPClientCertificate(t *testing.T) { + t.Parallel() + + serverCA, clientCA, otherCA := newTestCA(t, "server-ca"), newTestCA(t, "client-ca"), newTestCA(t, "other-ca") + good, _ := clientCA.pfx(t, "logic-client") + foreign, _ := otherCA.pfx(t, "intruder") + backend := mtlsBackend(t, serverCA, clientCA) + + tests := []struct { + auth la + name string + wantStatus armlogic.WorkflowStatus + wantCode string + wantBody string + }{ + { + name: "valid certificate", wantStatus: armlogic.WorkflowStatusSucceeded, + auth: la{"type": "ClientCertificate", "pfx": good, "password": certPassword}, + wantBody: "logic-client|TLS 1.3", + }, + { + name: "wrong password", wantStatus: armlogic.WorkflowStatusFailed, wantCode: "BadRequest", + auth: la{"type": "ClientCertificate", "pfx": good, "password": "nope"}, + }, + { + name: "not base64", wantStatus: armlogic.WorkflowStatusFailed, wantCode: "BadRequest", + auth: la{"type": "ClientCertificate", "pfx": "%%%", "password": certPassword}, + }, + { + name: "certificate from an untrusted issuer", wantStatus: armlogic.WorkflowStatusFailed, + wantCode: "ActionFailed", auth: la{"type": "ClientCertificate", "pfx": foreign, "password": certPassword}, + }, + { + name: "no certificate presented", wantStatus: armlogic.WorkflowStatusFailed, wantCode: "ActionFailed", + auth: la{"type": "None"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.prov.SetOutboundRootCAs(serverCA.pool) + s.create(t, "mtls", logicDef(requestTrigger(nil), la{"Call": la{ + "type": "Http", "runAfter": la{}, + "inputs": la{ + "method": "GET", "uri": backend.URL, "authentication": tc.auth, + "retryPolicy": la{"type": "none"}, + }, + }})) + + call := s.invoke(t, "mtls", `{}`).actions["Call"].Properties + assert.Equal(t, tc.wantStatus, *call.Status) + + if tc.wantCode != "" { + assert.Equal(t, tc.wantCode, *call.Code) + assert.NotContains(t, toJSON(t, call.Error), certPassword) + } + + if tc.wantBody != "" { + out, ok := s.content(t, call.OutputsLink).(map[string]any) + require.True(t, ok) + assert.True(t, strings.HasPrefix(out["body"].(string), "logic-client|TLS 1."), "%v", out["body"]) + } + }) + } +} + +func TestLogicHTTPClientCertificateSecretsNotRecorded(t *testing.T) { + t.Parallel() + + serverCA, clientCA := newTestCA(t, "server-ca"), newTestCA(t, "client-ca") + good, _ := clientCA.pfx(t, "logic-client") + backend := mtlsBackend(t, serverCA, clientCA) + + s := newLogicStack(t) + s.prov.SetOutboundRootCAs(serverCA.pool) + + def := logicDef(requestTrigger(nil), la{"Call": la{ + "type": "Http", "runAfter": la{}, + "inputs": la{ + "method": "GET", "uri": backend.URL, "retryPolicy": la{"type": "none"}, + "authentication": la{ + "type": "ClientCertificate", "pfx": "@parameters('pfxParam')", "password": "@parameters('passParam')", + }, + }, + }}) + def["parameters"] = la{ + "pfxParam": la{"type": "String", "defaultValue": good}, + "passParam": la{"type": "String", "defaultValue": certPassword}, + } + s.create(t, "secrets", def) + + out := s.invoke(t, "secrets", `{}`) + require.Equal(t, armlogic.WorkflowStatusSucceeded, *out.actions["Call"].Properties.Status) + + run := *out.run.Name + tr, err := s.factory.NewWorkflowRunActionsClient(). + NewListExpressionTracesPager(logicRG, "secrets", run, "Call", nil).NextPage(t.Context()) + require.NoError(t, err) + require.NotEmpty(t, tr.Inputs) + + for _, r := range tr.Inputs { + if strings.HasPrefix(*r.Path, "inputs.authentication") { + assert.Nil(t, r.Value) + } + } + + assert.NotContains(t, toJSON(t, tr), certPassword) + assert.NotContains(t, toJSON(t, tr), good) + assert.NotContains(t, toJSON(t, s.content(t, out.actions["Call"].Properties.InputsLink)), "authentication") + + for _, h := range s.requestHistories(t, "secrets", "Call") { + assert.NotContains(t, toJSON(t, h), certPassword) + } +} + +func TestLogicHTTPOAuthCertificate(t *testing.T) { + t.Parallel() + + ca := newTestCA(t, "client-ca") + pfx, cert := ca.pfx(t, "app") + otherPFX, _ := newTestCA(t, "other").pfx(t, "app") + sum := sha256.Sum256(cert.Raw) + + tests := []struct { + auth la + name string + wantStatus armlogic.WorkflowStatus + wantCode string + }{ + { + name: "certificate credential", wantStatus: armlogic.WorkflowStatusSucceeded, + auth: la{"credentialType": "Certificate", "pfx": pfx, "password": certPassword}, + }, + { + name: "assertion signed by another key is rejected", wantStatus: armlogic.WorkflowStatusFailed, + wantCode: "ActionFailed", + auth: la{"credentialType": "Certificate", "pfx": otherPFX, "password": certPassword}, + }, + { + name: "bad pfx", wantStatus: armlogic.WorkflowStatusFailed, wantCode: "BadRequest", + auth: la{"credentialType": "Certificate", "pfx": pfx, "password": "wrong"}, + }, + { + name: "pfx missing", wantStatus: armlogic.WorkflowStatusFailed, wantCode: "InvalidTemplate", + auth: la{"credentialType": "Certificate"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + gotAuth := make(chan string, 1) + backend := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + gotAuth <- r.Header.Get("Authorization") + })) + t.Cleanup(backend.Close) + + var authority *httptest.Server + + authority = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.NoError(t, r.ParseForm()) + assert.Equal(t, "/t1/oauth2/token", r.URL.Path) + assert.Equal(t, "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", + r.PostForm.Get("client_assertion_type")) + assert.Empty(t, r.PostForm.Get("client_secret")) + + claims := jwt.MapClaims{} + _, err := jwt.NewParser(jwt.WithValidMethods([]string{"RS256"}), jwt.WithoutClaimsValidation()). + ParseWithClaims( + r.PostForm.Get("client_assertion"), claims, + func(tok *jwt.Token) (any, error) { + assert.Len(t, tok.Header["x5t"], 27, "SHA-1 thumbprint, base64url") + if tc.wantCode == "" { + assert.Equal(t, base64.RawURLEncoding.EncodeToString(sum[:]), tok.Header["x5t#S256"]) + } + + return cert.PublicKey, nil + }) + if err != nil { + http.Error(w, `{"error":"invalid_client"}`, http.StatusUnauthorized) + + return + } + + assert.Equal(t, "cid", claims["iss"]) + assert.Equal(t, "cid", claims["sub"]) + assert.Equal(t, authority.URL+"/t1/oauth2/token", claims["aud"]) + + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"token_type":"Bearer","access_token":"cert-tok"}`)) + })) + t.Cleanup(authority.Close) + + auth := tc.auth + auth["type"], auth["authority"] = "ActiveDirectoryOAuth", authority.URL+"/" + auth["tenant"], auth["audience"], auth["clientId"] = "t1", "https://aud/", "cid" + + s := newLogicStack(t) + s.create(t, "oauthcert", logicDef(requestTrigger(nil), la{"Call": la{ + "type": "Http", "runAfter": la{}, + "inputs": la{ + "method": "GET", "uri": backend.URL, "authentication": auth, "retryPolicy": la{"type": "none"}, + }, + }})) + + call := s.invoke(t, "oauthcert", `{}`).actions["Call"].Properties + require.Equal(t, tc.wantStatus, *call.Status, "%s", toJSON(t, call.Error)) + + if tc.wantCode != "" { + assert.Equal(t, tc.wantCode, *call.Code) + + return + } + + assert.Equal(t, "Bearer cert-tok", <-gotAuth) + }) + } +} diff --git a/services/azurearm/logic_http_oauth_test.go b/services/azurearm/logic_http_oauth_test.go index e0012547a3..a1c1351fd4 100644 --- a/services/azurearm/logic_http_oauth_test.go +++ b/services/azurearm/logic_http_oauth_test.go @@ -34,9 +34,9 @@ func TestLogicHTTPActiveDirectoryOAuth(t *testing.T) { auth: la{"tenant": "t1", "audience": "https://aud/", "clientId": "cid", "secret": "wrong"}, }, { - name: "certificate credential is refused", + name: "certificate credential with an undecodable pfx", wantStatus: armlogic.WorkflowStatusFailed, - wantCode: "InvalidTemplate", + wantCode: "BadRequest", auth: la{ "tenant": "t1", "audience": "a", diff --git a/services/azurearm/logic_http_trigger_test.go b/services/azurearm/logic_http_trigger_test.go new file mode 100644 index 0000000000..e76c948926 --- /dev/null +++ b/services/azurearm/logic_http_trigger_test.go @@ -0,0 +1,270 @@ +package azurearm_test + +import ( + "net/http" + "net/http/httptest" + "strconv" + "sync" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func httpTriggerDef(uri string) la { + return logicDef(la{"poll": la{ + "type": "Http", + "recurrence": la{"frequency": "Minute", "interval": 1, "startTime": "2026-01-01T00:00:00Z"}, + "inputs": la{"method": "GET", "uri": uri, "headers": la{"X-Poll": "1"}, "retryPolicy": la{"type": "none"}}, + }}, la{"Mark": compose("@triggerBody()", nil)}) +} + +type pollBackend struct { + reply func(n int, w http.ResponseWriter) + paths []string + hdrs []string + mu sync.Mutex +} + +func (b *pollBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + b.paths = append(b.paths, r.URL.Path) + b.hdrs = append(b.hdrs, r.Header.Get("X-Poll")+"|"+r.Header.Get("X-Ms-Workflow-Name")) + n := len(b.paths) + b.mu.Unlock() + + b.reply(n, w) +} + +func (b *pollBackend) seen() []string { + b.mu.Lock() + defer b.mu.Unlock() + + return append([]string(nil), b.paths...) +} + +func (s *logicStack) pollHistories(t *testing.T, wf string) []*armlogic.WorkflowTriggerHistory { + t.Helper() + + page, err := s.factory.NewWorkflowTriggerHistoriesClient().NewListPager(logicRG, wf, "poll", nil). + NextPage(t.Context()) + require.NoError(t, err) + + return page.Value +} + +func TestLogicHTTPPollingTrigger(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + reply func(n int, w http.ResponseWriter) + steps []time.Duration + wantPaths []string + wantRuns int + wantSkip int + }{ + { + name: "200 starts a run", + reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"n":1}`)) + }, + steps: []time.Duration{time.Minute}, wantPaths: []string{"/poll"}, wantRuns: 1, + }, + { + name: "202 does not start a run", + reply: func(_ int, w http.ResponseWriter) { w.WriteHeader(http.StatusAccepted) }, + steps: []time.Duration{time.Minute}, wantPaths: []string{"/poll"}, wantSkip: 1, + }, + { + name: "404 does not start a run", + reply: func(_ int, w http.ResponseWriter) { w.WriteHeader(http.StatusNotFound) }, + steps: []time.Duration{time.Minute}, wantPaths: []string{"/poll"}, wantSkip: 1, + }, + { + name: "location header is the next poll url", + reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Location", "/next") + _, _ = w.Write([]byte("x")) + }, + steps: []time.Duration{time.Minute, time.Minute}, wantPaths: []string{"/poll", "/next"}, wantRuns: 2, + }, + { + name: "retry-after longer than the recurrence delays the next poll", + reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Retry-After", "150") + w.WriteHeader(http.StatusAccepted) + }, + steps: []time.Duration{time.Minute, time.Minute, time.Minute, time.Minute}, + wantPaths: []string{"/poll", "/poll"}, wantSkip: 2, + }, + { + name: "retry-after shorter than the recurrence keeps the recurrence", + reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Retry-After", "5") + w.WriteHeader(http.StatusAccepted) + }, + steps: []time.Duration{time.Minute, time.Minute}, wantPaths: []string{"/poll", "/poll"}, wantSkip: 2, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &pollBackend{reply: tc.reply} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "poller", httpTriggerDef(srv.URL+"/poll")) + s.clock.Advance(0) + + for _, d := range tc.steps { + s.clock.Advance(d) + s.waitRuns(t) + } + + assert.Equal(t, tc.wantPaths, b.seen()) + assert.Equal(t, tc.wantRuns, s.runCount(t, "poller")) + + skipped := 0 + + for _, h := range s.pollHistories(t, "poller") { + if *h.Properties.Status == armlogic.WorkflowStatusSkipped { + skipped++ + + assert.False(t, *h.Properties.Fired) + } + } + + assert.Equal(t, tc.wantSkip, skipped) + + b.mu.Lock() + defer b.mu.Unlock() + + for _, h := range b.hdrs { + assert.Equal(t, "1|poller", h) + } + }) + } +} + +func TestLogicHTTPPollingTriggerOutputs(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + srv := httptest.NewServer(&pollBackend{reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.Header().Set("X-Reply", "yes") + _, _ = w.Write([]byte(`{"n":42}`)) + }}) + t.Cleanup(srv.Close) + + s.create(t, "poller", httpTriggerDef(srv.URL)) + s.clock.Advance(0) + s.clock.Advance(time.Minute) + s.waitRuns(t) + + run := s.latestRun(t, "poller") + assert.Equal(t, "poll", *run.Properties.Trigger.Name) + + out, ok := s.content(t, run.Properties.Trigger.OutputsLink).(map[string]any) + require.True(t, ok) + assert.InDelta(t, 200, out["statusCode"], 0) + assert.Equal(t, map[string]any{"n": float64(42)}, out["body"]) + + hdr, _ := out["headers"].(map[string]any) + assert.Equal(t, "yes", hdr["X-Reply"]) + + assert.Equal( + t, + map[string]any{"n": float64(42)}, + s.content(t, s.actions(t, "poller")["Mark"].Properties.OutputsLink), + ) +} + +func TestLogicHTTPPollingTriggerRunAndDisable(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &pollBackend{reply: func(_ int, w http.ResponseWriter) { _, _ = w.Write([]byte("hi")) }} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "poller", httpTriggerDef(srv.URL+"/poll")) + + tc := s.factory.NewWorkflowTriggersClient() + _, err := tc.Run(t.Context(), logicRG, "poller", "poll", nil) + require.NoError(t, err) + s.waitRuns(t) + assert.Equal(t, 1, s.runCount(t, "poller"), "Run polls the endpoint now") + assert.Equal(t, []string{"/poll"}, b.seen()) + + _, err = s.factory.NewWorkflowsClient().Disable(t.Context(), logicRG, "poller", nil) + require.NoError(t, err) + s.clock.Advance(0) + s.clock.Advance(5 * time.Minute) + s.waitRuns(t) + assert.Len(t, b.seen(), 1, "a disabled workflow does not poll") + + _, err = tc.Run(t.Context(), logicRG, "poller", "poll", nil) + require.Error(t, err) +} + +func TestLogicHTTPPollingTriggerRefusesExternalHost(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "poller", httpTriggerDef("http://203.0.113.9/poll")) + s.clock.Advance(0) + s.clock.Advance(time.Minute) + s.waitRuns(t) + + assert.Equal(t, 0, s.runCount(t, "poller")) + + hs := s.pollHistories(t, "poller") + require.Len(t, hs, 1) + assert.Equal(t, armlogic.WorkflowStatusFailed, *hs[0].Properties.Status) + assert.Equal(t, "TriggerRequestFailed", *hs[0].Properties.Code) +} + +func TestLogicHTTPTriggerValidation(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + rec := la{"frequency": "Minute", "interval": 1} + + tests := []struct { + inputs la + rec la + name string + }{ + {name: "no uri", inputs: la{"method": "GET"}, rec: rec}, + {name: "bad method", inputs: la{"method": "FETCH", "uri": "http://x"}, rec: rec}, + {name: "no recurrence", inputs: la{"method": "GET", "uri": "http://x"}}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + trig := la{"type": "Http", "inputs": tc.inputs} + if tc.rec != nil { + trig["recurrence"] = tc.rec + } + + _, err := s.factory.NewWorkflowsClient(). + CreateOrUpdate(t.Context(), logicRG, "bad"+strconv.Itoa(len(tc.name)), + armlogic.Workflow{ + Location: new("westus"), + Properties: &armlogic.WorkflowProperties{Definition: logicDef(la{"poll": trig}, la{})}, + }, nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "InvalidTemplate") + }) + } +} diff --git a/services/azurearm/logic_locales_internal_test.go b/services/azurearm/logic_locales_internal_test.go new file mode 100644 index 0000000000..2c8847ac9f --- /dev/null +++ b/services/azurearm/logic_locales_internal_test.go @@ -0,0 +1,185 @@ +package azurearm + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLogicLocaleStandardFormats(t *testing.T) { + t.Parallel() + + tests := []struct { + want map[string]string + locale string + }{ + { + map[string]string{ + "d": "05/03/2024", "D": "Tuesday, 5 March 2024", "g": "05/03/2024 14:07", "T": "14:07:09", + }, + "en-GB", + }, + { + map[string]string{"d": "05.03.2024", "D": "Dienstag, 5. März 2024", "f": "Dienstag, 5. März 2024 14:07"}, + "de-DE", + }, + {map[string]string{"d": "05/03/2024", "D": "martedì 5 marzo 2024", "t": "14:07"}, "it-IT"}, + {map[string]string{"d": "05/03/2024", "D": "terça-feira, 5 de março de 2024"}, "pt-BR"}, + {map[string]string{"d": "05/03/2024", "D": "terça-feira, 5 de março de 2024"}, "pt-PT"}, + {map[string]string{"d": "05-03-2024", "D": "dinsdag 5 maart 2024"}, "nl-NL"}, + {map[string]string{"d": "2024-03-05", "D": "tisdag 5 mars 2024"}, "sv-SE"}, + {map[string]string{"d": "05/03/2024", "D": "tirsdag den 5. marts 2024"}, "da-DK"}, + {map[string]string{"d": "05.03.2024", "D": "tirsdag 5. mars 2024"}, "nb-NO"}, + {map[string]string{"d": "5.3.2024", "D": "tiistaina 5. maaliskuuta 2024", "t": "14.07"}, "fi-FI"}, + {map[string]string{"d": "05.03.2024", "D": "wtorek, 5 marca 2024"}, "pl-PL"}, + {map[string]string{"d": "2024/03/05", "D": "2024年3月5日火曜日", "t": "14:07"}, "ja-JP"}, + {map[string]string{"d": "2024/3/5", "D": "2024年3月5日星期二", "t": "下午2:07"}, "zh-CN"}, + {map[string]string{"d": "2024. 3. 5.", "D": "2024년 3월 5일 화요일", "t": "오후 2:07"}, "ko-KR"}, + {map[string]string{"d": "05.03.2024", "D": "вторник, 5 марта 2024 г."}, "ru-RU"}, + {map[string]string{"d": "5.03.2024", "D": "5 Mart 2024 Salı"}, "tr-TR"}, + {map[string]string{"d": "05/03/2024", "D": "mardi 5 mars 2024"}, "fr-FR"}, + {map[string]string{"d": "5/3/2024", "D": "martes, 5 de marzo de 2024"}, "es-ES"}, + { + map[string]string{"d": "3/5/2024", "g": "3/5/2024 2:07 PM", "G": "3/5/2024 2:07:09 PM", "t": "2:07 PM"}, + "en-US", + }, + } + + for _, tc := range tests { + t.Run(tc.locale, func(t *testing.T) { + t.Parallel() + + for spec, want := range tc.want { + got, err := formatLogicTime(stampLogicTS(t), spec, tc.locale) + require.NoError(t, err) + assert.Equal(t, want, got, spec) + } + }) + } +} + +const logicTestStamp = "2024-03-05T14:07:09Z" + +func stampLogicTS(t *testing.T) logicTS { + t.Helper() + + ts, err := parseLogicTime(logicTestStamp) + require.NoError(t, err) + + return ts +} + +func TestLogicLocaleInvariantFormats(t *testing.T) { + t.Parallel() + + ts := stampLogicTS(t) + + tests := []struct { + spec, want string + }{ + {"R", "Tue, 05 Mar 2024 14:07:09 GMT"}, + {"r", "Tue, 05 Mar 2024 14:07:09 GMT"}, + {"s", "2024-03-05T14:07:09"}, + {"u", "2024-03-05 14:07:09Z"}, + {"o", "2024-03-05T14:07:09.0000000Z"}, + } + + for _, loc := range []string{"de-DE", "ja-JP", "tr-TR"} { + for _, tc := range tests { + t.Run(loc+"/"+tc.spec, func(t *testing.T) { + t.Parallel() + + got, err := formatLogicTime(ts, tc.spec, loc) + require.NoError(t, err) + assert.Equal(t, tc.want, got, "the %s specifier ignores the culture", tc.spec) + }) + } + } +} + +func TestLogicLocaleRoundTrip(t *testing.T) { + t.Parallel() + + locales := []string{ + "en-GB", "fr-FR", "es-ES", "de-DE", "it-IT", "pt-BR", "pt-PT", "nl-NL", "sv-SE", "da-DK", "nb-NO", "fi-FI", + "pl-PL", "ja-JP", "zh-CN", "ko-KR", "ru-RU", "tr-TR", + } + + for _, loc := range locales { + for _, spec := range []string{"d", "D", "g", "G", "f", "F"} { + t.Run(loc+"/"+spec, func(t *testing.T) { + t.Parallel() + + text, err := formatLogicTime(stampLogicTS(t), spec, loc) + require.NoError(t, err) + + ts, ok := parseWithFormat(text, spec, logicLocales[lower(loc)]) + require.True(t, ok, "%q must parse back under %s", text, spec) + + want := stampLogicTS(t).t + switch spec { + case "d", "D": + want = want.Truncate(24 * 60 * 60 * 1e9) + case "g", "f": + want = want.Add(-9 * 1e9) + } + + assert.Equal(t, want, ts.t) + }) + } + } +} + +func lower(s string) string { + b := []byte(s) + for i, c := range b { + if c >= 'A' && c <= 'Z' { + b[i] = c + 'a' - 'A' + } + } + + return string(b) +} + +func TestLogicLocaleExpressions(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + expr string + want string + }{ + {"de month", "@formatDateTime('2024-03-05', 'MMMM', 'de-DE')", "März"}, + {"de abbreviated month", "@formatDateTime('2024-03-05', 'MMM', 'de-DE')", "März"}, + {"fr abbreviated month", "@formatDateTime('2024-07-05', 'MMM', 'fr-FR')", "juil."}, + {"ru day", "@formatDateTime('2024-03-05', 'dddd', 'ru-RU')", "вторник"}, + {"ja meridiem", "@formatDateTime('2024-03-05T14:00:00', 'tt h', 'ja-JP')", "午後 2"}, + {"zh meridiem", "@formatDateTime('2024-03-05T09:00:00', 'tt h', 'zh-CN')", "上午 9"}, + {"en-GB lowercase", "@formatDateTime('2024-03-05T14:00:00', 'tt', 'en-GB')", "pm"}, + {"non ascii literal", "@formatDateTime('2024-03-05', 'yyyy年M月', 'ja-JP')", "2024年3月"}, + {"parse de", "@parseDateTime('5. März 2024', 'de-DE')", "2024-03-05T00:00:00.0000000"}, + {"parse ja", "@parseDateTime('2024/03/05', 'ja-JP')", "2024-03-05T00:00:00.0000000"}, + {"parse ru standard", "@parseDateTime('05.03.2024 14:07', 'ru-RU', 'g')", "2024-03-05T14:07:00.0000000"}, + {"parse ko meridiem", "@parseDateTime('오후 2:07', 'ko-KR', 'tt h:mm')", "0001-01-01T14:07:00.0000000"}, + {"R format", "@formatDateTime('2024-03-05T14:07:09Z', 'R')", "Tue, 05 Mar 2024 14:07:09 GMT"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + got, err := evalLogicTemplate(tc.expr, logicTestCtx()) + require.NoError(t, err) + assert.Equal(t, tc.want, got) + }) + } + + for _, expr := range []string{ + "@formatDateTime('2024-03-05', 'd', 'xx-XX')", + "@parseDateTime('05.03.2024', 'th-TH')", + } { + _, err := evalLogicTemplate(expr, logicTestCtx()) + require.Error(t, err, "locales outside the table keep being rejected") + } +} diff --git a/services/azurearm/logic_pfx_internal_test.go b/services/azurearm/logic_pfx_internal_test.go new file mode 100644 index 0000000000..4492cf9285 --- /dev/null +++ b/services/azurearm/logic_pfx_internal_test.go @@ -0,0 +1,113 @@ +package azurearm + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "math/big" + "testing" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + pkcs12 "software.sslmate.com/src/go-pkcs12" +) + +func testPFX(t *testing.T, key any, pub any, password string) map[string]any { + t.Helper() + + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(7), Subject: pkix.Name{CommonName: "app"}, + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, key) + require.NoError(t, err) + + cert, err := x509.ParseCertificate(der) + require.NoError(t, err) + + raw, err := pkcs12.Modern2023.Encode(key, cert, nil, password) + require.NoError(t, err) + + return map[string]any{"pfx": base64.StdEncoding.EncodeToString(raw), "password": password} +} + +func TestLogicClientAssertionClaims(t *testing.T) { + t.Parallel() + + rk, err := rsa.GenerateKey(rand.Reader, 2048) + require.NoError(t, err) + + pfx, err := loadLogicPFX(testPFX(t, rk, &rk.PublicKey, "pw")) + require.NoError(t, err) + + now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC) + seen := map[string]bool{} + + for range 3 { + raw, aerr := pfx.clientAssertion("cid", "https://login.example/t/oauth2/token", now) + require.NoError(t, aerr) + + claims := jwt.MapClaims{} + _, perr := jwt.NewParser(jwt.WithValidMethods([]string{"RS256"}), jwt.WithoutClaimsValidation()). + ParseWithClaims(raw, claims, func(*jwt.Token) (any, error) { return &rk.PublicKey, nil }) + require.NoError(t, perr) + + jti, _ := claims["jti"].(string) + assert.NotEmpty(t, jti) + assert.False(t, seen[jti], "jti is unique per assertion") + + seen[jti] = true + + assert.Equal(t, "cid", claims["iss"]) + assert.Equal(t, "cid", claims["sub"]) + assert.Equal(t, "https://login.example/t/oauth2/token", claims["aud"]) + assert.InDelta(t, float64(now.Unix()), claims["nbf"], 0) + assert.InDelta(t, float64(now.Add(logicAssertionTTL).Unix()), claims["exp"], 0) + } +} + +func TestLogicLoadPFX(t *testing.T) { + t.Parallel() + + ek, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + good := testPFX(t, ek, &ek.PublicKey, "pw") + + tests := []struct { + auth map[string]any + name string + wantLoadErr bool + }{ + {name: "ecdsa key loads for tls", auth: good}, + {name: "wrong password", auth: map[string]any{"pfx": good["pfx"], "password": "nope"}, wantLoadErr: true}, + {name: "not base64", auth: map[string]any{"pfx": "!!!", "password": "pw"}, wantLoadErr: true}, + {name: "empty", auth: map[string]any{}, wantLoadErr: true}, + {name: "not a pfx", auth: map[string]any{"pfx": "AAAA", "password": "pw"}, wantLoadErr: true}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + pfx, lerr := loadLogicPFX(tc.auth) + if tc.wantLoadErr { + require.ErrorIs(t, lerr, errLogicClientCert) + assert.NotContains(t, lerr.Error(), "pw") + + return + } + + require.NoError(t, lerr) + + _, aerr := pfx.clientAssertion("cid", "aud", time.Now()) + require.ErrorIs(t, aerr, errLogicClientCert, "an ECDSA key cannot sign the RS256 assertion") + }) + } +} diff --git a/services/azurearm/logic_secure_test.go b/services/azurearm/logic_secure_test.go index 3b6b541d05..a870bebe9d 100644 --- a/services/azurearm/logic_secure_test.go +++ b/services/azurearm/logic_secure_test.go @@ -83,7 +83,7 @@ func TestLogicSecureOutputsPropagate(t *testing.T) { "runAfter": la{}, "inputs": la{ "method": "GET", - "uri": "http://127.0.0.1:1/x", + "uri": "http://203.0.113.9/x", "retryPolicy": la{"type": "none"}, }, "runtimeConfiguration": secureCfg("outputs"), @@ -170,7 +170,7 @@ func TestLogicStaticResult(t *testing.T) { def := logicDef(requestTrigger(nil), la{ "Call": la{ "type": "Http", "runAfter": la{}, - "inputs": la{"method": "GET", "uri": "http://127.0.0.1:1/never", "retryPolicy": la{"type": "none"}}, + "inputs": la{"method": "GET", "uri": "http://203.0.113.9/never", "retryPolicy": la{"type": "none"}}, "runtimeConfiguration": la{ "staticResult": la{"name": "Call0", "staticResultOptions": "Enabled"}, }, diff --git a/services/azurearm/logic_security_internal_test.go b/services/azurearm/logic_security_internal_test.go new file mode 100644 index 0000000000..e569ff5ac9 --- /dev/null +++ b/services/azurearm/logic_security_internal_test.go @@ -0,0 +1,198 @@ +package azurearm + +import ( + "strings" + "testing" + "unicode/utf8" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLogicLocaleTableDecodes(t *testing.T) { + t.Parallel() + + got, err := decodeLogicLocales(logicLocaleTable) + require.NoError(t, err) + assert.Len(t, got, 19) + + for key, l := range got { + assert.NotEmpty(t, l.am, key) + assert.NotEmpty(t, l.pm, key) + assert.Len(t, l.std, len(logicLocaleStd), key) + } +} + +func TestLogicLocaleTableRejectsMalformedRows(t *testing.T) { + t.Parallel() + + good := strings.Split(strings.Split(logicLocaleTable, "\n")[1], "\t") + require.Len(t, good, logicLocaleCols) + + tests := []struct { + mutate func(c []string) + name string + cut bool + }{ + {name: "missing column", cut: true}, + {name: "short month list", mutate: func(c []string) { c[1] = "a|b" }}, + {name: "empty month name", mutate: func(c []string) { c[2] = strings.Replace(c[2], "Jan", "", 1) }}, + {name: "short day list", mutate: func(c []string) { c[3] = "x" }}, + {name: "short standard patterns", mutate: func(c []string) { c[7] = "d|D" }}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + row := append([]string(nil), good...) + if tc.cut { + row = row[:len(row)-1] + } else { + tc.mutate(row) + } + + _, err := decodeLogicLocales("# header\n" + strings.Join(row, "\t") + "\n") + require.ErrorIs(t, err, errLogicLocaleRow) + assert.Contains(t, err.Error(), "line 2") + }) + } +} + +func TestLogicLocaleNameMatchKeepsRuneBoundaries(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + input string + names []string + wantPos int + wantIdx int + wantOK bool + }{ + {"kelvin sign", "\u212aa", []string{"ka"}, len("\u212aa"), 0, true}, + {"dotted capital i is not an i", "İx", []string{"i"}, 0, 0, false}, + {"umlaut upper", "MÄRZ 2024", []string{"Januar", "März"}, len("MÄRZ"), 1, true}, + {"longest wins", "Juni", []string{"Jun", "Juni"}, len("Juni"), 1, true}, + {"cyrillic upper", "МАРТА 5", []string{"марта"}, len("МАРТА"), 0, true}, + {"no match", "xyz", []string{"abc"}, 0, 0, false}, + {"truncated input", "ma", []string{"mars"}, 0, 0, false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + sc := &timeScanner{s: tc.input} + idx, ok := sc.name(tc.names) + assert.Equal(t, tc.wantOK, ok) + assert.Equal(t, tc.wantIdx, idx) + assert.Equal(t, tc.wantPos, sc.pos) + assert.True(t, utf8.ValidString(tc.input[sc.pos:]), "the cursor stays on a rune boundary") + }) + } +} + +func TestLogicLocaleMeridiemFoldsCase(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + input string + am, pm string + wantPM bool + wantOK bool + pos int + }{ + {"upper pm", "PM 1", "am", "pm", true, true, 2}, + {"korean", "오후 2", "오전", "오후", true, true, len("오후")}, + {"russian upper", "ДП 1", "дп", "пп", false, true, len("ДП")}, + {"none", "xx", "am", "pm", false, false, 0}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + sc := &timeScanner{s: tc.input, loc: logicLocale{am: tc.am, pm: tc.pm}} + pt := &parsedTime{} + assert.Equal(t, tc.wantOK, sc.meridiem(pt)) + assert.Equal(t, tc.wantPM, pt.pm) + assert.Equal(t, tc.pos, sc.pos) + }) + } +} + +func TestLogicValidBase(t *testing.T) { + t.Parallel() + + tests := []struct { + base string + want bool + }{ + {"https://127.0.0.1:8443", true}, + {"https://[::1]:8443", true}, + {"https://localhost:10006", true}, + {"https://host.docker.internal:4566", true}, + {"https://gopherstack.default.svc.cluster.local:443", true}, + {"https://user@evil.example.com:443", false}, + {"https://evil.example.com:443/x", false}, + {"https://evil.example.com:443?x=1", false}, + {"https://evil.example.com:99999", false}, + {"https://evil exam.com:443", false}, + {"http://evil.example.com:443", false}, + {"https://:443", false}, + {"", false}, + } + + for _, tc := range tests { + t.Run(tc.base, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tc.want, validBase(tc.base)) + }) + } +} + +func TestLogicSecretTracePath(t *testing.T) { + t.Parallel() + + tests := []struct { + path string + want bool + }{ + {"inputs.authentication", true}, + {"inputs.Authentication.pfx", true}, + {"inputs.headers.Authorization", true}, + {"inputs.headers.cookie", true}, + {"inputs.cookie", true}, + {"inputs.headers.X-Keep", false}, + {"inputs.body", false}, + } + + for _, tc := range tests { + t.Run(tc.path, func(t *testing.T) { + t.Parallel() + + assert.Equal(t, tc.want, secretTracePath(tc.path)) + }) + } +} + +func TestLogicRunBudget(t *testing.T) { + t.Parallel() + + var b logicRunBudget + + assert.True(t, b.takeBody(logicMaxRunBodyBytes)) + assert.False(t, b.takeBody(1)) + + for range logicMaxRunRequests { + require.True(t, b.takeRequest()) + } + + assert.False(t, b.takeRequest()) + assert.Equal(t, 5, b.takeTraces(5)) + assert.Equal(t, logicMaxRunTraces-5, b.takeTraces(logicMaxRunTraces)) + assert.Zero(t, b.takeTraces(1)) +} diff --git a/services/azurearm/logic_security_test.go b/services/azurearm/logic_security_test.go new file mode 100644 index 0000000000..7ed624ce9e --- /dev/null +++ b/services/azurearm/logic_security_test.go @@ -0,0 +1,422 @@ +package azurearm_test + +import ( + "net/http" + "net/http/httptest" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type logicSeenRequest struct { + method, auth, cookie, poll, workflow string +} + +type logicRecordingBackend struct { + reply func(n int, w http.ResponseWriter) + seen []logicSeenRequest + mu sync.Mutex +} + +func (b *logicRecordingBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b.mu.Lock() + b.seen = append(b.seen, logicSeenRequest{ + method: r.Method, auth: r.Header.Get("Authorization"), cookie: r.Header.Get("Cookie"), + poll: r.Header.Get("X-Poll"), workflow: r.Header.Get("X-Ms-Workflow-Name"), + }) + n := len(b.seen) + b.mu.Unlock() + + if b.reply != nil { + b.reply(n, w) + } +} + +func (b *logicRecordingBackend) requests() []logicSeenRequest { + b.mu.Lock() + defer b.mu.Unlock() + + return append([]logicSeenRequest(nil), b.seen...) +} + +func authedPollDef(uri string) la { + return logicDef(la{"poll": la{ + "type": "Http", + "recurrence": la{"frequency": "Minute", "interval": 1, "startTime": "2026-01-01T00:00:00Z"}, + "inputs": la{ + "method": "GET", "uri": uri, "headers": la{"X-Poll": "1"}, "cookie": "sid=1", + "authentication": la{"type": "Raw", "value": "Bearer sek"}, "retryPolicy": la{"type": "none"}, + }, + }}, la{"Mark": compose("@triggerBody()", nil)}) +} + +func (s *logicStack) pollSteps(t *testing.T, steps ...time.Duration) { + t.Helper() + + s.clock.Advance(0) + + for _, d := range steps { + s.clock.Advance(d) + s.waitRuns(t) + } +} + +func TestLogicPollLocationOtherOriginKeepsCredentials(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + other := &logicRecordingBackend{} + otherSrv := httptest.NewServer(other) + t.Cleanup(otherSrv.Close) + + first := &logicRecordingBackend{reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Location", otherSrv.URL+"/next") + _, _ = w.Write([]byte("x")) + }} + firstSrv := httptest.NewServer(first) + t.Cleanup(firstSrv.Close) + + s.create(t, "poller", authedPollDef(firstSrv.URL+"/poll")) + s.pollSteps(t, time.Minute, time.Minute) + + f := first.requests() + require.Len(t, f, 1) + assert.Equal(t, "Bearer sek", f[0].auth, "the configured endpoint receives the credential") + + o := other.requests() + require.Len(t, o, 1) + assert.Equal(t, http.MethodGet, o[0].method) + assert.Empty(t, o[0].auth, "a Location on another origin never receives the credential") + assert.Empty(t, o[0].cookie) + assert.Empty(t, o[0].poll) + assert.Equal(t, "poller", o[0].workflow) +} + +func TestLogicPollLocationExternalHostFailsTrigger(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + first := &logicRecordingBackend{reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Location", "http://203.0.113.9/next") + _, _ = w.Write([]byte("x")) + }} + srv := httptest.NewServer(first) + t.Cleanup(srv.Close) + + s.create(t, "poller", authedPollDef(srv.URL+"/poll")) + s.pollSteps(t, time.Minute, time.Minute) + + assert.Equal(t, 1, s.runCount(t, "poller")) + + failed := 0 + + for _, h := range s.pollHistories(t, "poller") { + if *h.Properties.Status == armlogic.WorkflowStatusFailed { + failed++ + + assert.Equal(t, "TriggerRequestFailed", *h.Properties.Code) + } + } + + assert.Equal(t, 1, failed, "the poll of a disallowed Location is a failed trigger") +} + +func TestLogicPollRetryAfter(t *testing.T) { + t.Parallel() + + tests := []struct { + header func(now time.Time) string + name string + steps []time.Duration + wantPolls int + }{ + { + name: "http date", + header: func(now time.Time) string { return now.Add(150 * time.Second).UTC().Format(http.TimeFormat) }, + steps: []time.Duration{time.Minute, time.Minute, time.Minute, time.Minute}, + wantPolls: 2, + }, + { + name: "past http date keeps the recurrence", + header: func(now time.Time) string { return now.Add(-time.Hour).UTC().Format(http.TimeFormat) }, + steps: []time.Duration{time.Minute, time.Minute}, + wantPolls: 2, + }, + { + name: "absurd seconds are clamped", + header: func(time.Time) string { return strconv.Itoa(1<<31 - 1) }, + steps: []time.Duration{time.Minute, 25 * time.Hour}, + wantPolls: 2, + }, + { + name: "beyond int32 seconds are clamped", + header: func(time.Time) string { return "99999999999999" }, + steps: []time.Duration{time.Minute, 25 * time.Hour}, + wantPolls: 2, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &logicRecordingBackend{reply: func(_ int, w http.ResponseWriter) { + w.Header().Set("Retry-After", tc.header(s.clock.Now())) + w.WriteHeader(http.StatusAccepted) + }} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "poller", httpTriggerDef(srv.URL+"/poll")) + s.pollSteps(t, tc.steps...) + + assert.Len(t, b.requests(), tc.wantPolls) + }) + } +} + +func (s *logicStack) postWithHost(t *testing.T, path, host string) { + t.Helper() + + full := s.url + "/subscriptions/" + aciSub + "/resourceGroups/" + logicRG + + "/providers/Microsoft.Logic" + path + "?api-version=2019-05-01" + req, err := http.NewRequestWithContext(t.Context(), http.MethodPost, full, nil) + require.NoError(t, err) + + req.Host = host + + resp, err := s.client.Do(req) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + require.Equal(t, http.StatusOK, resp.StatusCode) +} + +func TestLogicWebhookCallbackHost(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + host string + wantBase string + }{ + { + name: "service fqdn", host: "gopherstack.default.svc.cluster.local:443", + wantBase: "https://gopherstack.default.svc.cluster.local:443", + }, + {name: "docker host", host: "host.docker.internal:4566", wantBase: "https://host.docker.internal:4566"}, + {name: "userinfo refused", host: "user@evil.example.com:443"}, + {name: "bad characters refused", host: "evil.example.com/x:443"}, + {name: "bad port refused", host: "evil.example.com:99999"}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &hookBackend{} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "hooked", webhookDef(srv.URL, "")) + s.waitRuns(t) + + _, err := s.factory.NewWorkflowsClient().Disable(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + s.postWithHost(t, "/workflows/hooked/enable", tc.host) + s.waitRuns(t) + + calls := b.seen() + require.Len(t, calls, 3, "subscribe, unsubscribe, subscribe") + + if tc.wantBase != "" { + assert.True(t, strings.HasPrefix(calls[2].callback, tc.wantBase+"/_logic/workflows/"), + calls[2].callback) + + return + } + + assert.True(t, strings.HasPrefix(calls[2].callback, s.url+"/_logic/workflows/"), + "a refused host keeps the base of the workflow's earlier write: %s", calls[2].callback) + }) + } +} + +func TestLogicWebhookCallbackHostIsPerWorkflow(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &hookBackend{} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "hooked", webhookDef(srv.URL, "")) + s.create(t, "other", logicDef(requestTrigger(nil), la{"Mark": compose("1", nil)})) + s.waitRuns(t) + + _, err := s.factory.NewWorkflowsClient().Disable(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + + s.postWithHost(t, "/workflows/other/disable", "evil.example.com:443") + + _, err = s.factory.NewWorkflowsClient().Enable(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + + calls := b.seen() + require.Len(t, calls, 3) + assert.True(t, strings.HasPrefix(calls[2].callback, s.url+"/_logic/workflows/"), calls[2].callback) +} + +func TestLogicResetDropsQueuedWebhookCalls(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + + var ( + mu sync.Mutex + paths []string + started = make(chan struct{}) + release = make(chan struct{}) + once sync.Once + ) + + srv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + mu.Lock() + paths = append(paths, r.URL.Path) + mu.Unlock() + + once.Do(func() { + close(started) + <-release + }) + })) + t.Cleanup(srv.Close) + + s.create(t, "one", webhookDef(srv.URL+"/one", "")) + <-started + s.create(t, "two", webhookDef(srv.URL+"/two", "")) + + s.prov.Reset() + close(release) + s.waitRuns(t) + + mu.Lock() + defer mu.Unlock() + + assert.Equal(t, []string{"/one/sub", "/one/unsub"}, paths, + "the queued subscribe is dropped and the subscribe that finished after the reset is undone") +} + +func TestLogicExpressionTracesHideSecrets(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + def := logicDef(requestTrigger(nil), la{"Act": la{ + "type": "Compose", "runAfter": la{}, + "inputs": la{ + "a": "@concat('p-', parameters('sec'))", + "b": "x@{parameters('sec')}y", + "headers": la{ + "Authorization": "@concat('Bearer ', parameters('tok'))", "Cookie": "@concat('sid=', parameters('ck'))", + }, + "ok": "@add(1, 2)", + }, + }}) + def["parameters"] = la{ + "sec": la{"type": "SecureString", "defaultValue": "TOPSECRETVALUE"}, + "tok": la{"type": "String", "defaultValue": "zzzbearer"}, + "ck": la{"type": "String", "defaultValue": "zzzcookie"}, + } + + s.create(t, "trace", def) + s.invoke(t, "trace", `{}`) + + res, err := s.factory.NewWorkflowRunActionsClient(). + NewListExpressionTracesPager(logicRG, "trace", s.latestRunName(t, "trace"), "Act", nil). + NextPage(t.Context()) + require.NoError(t, err) + + raw := toJSON(t, res) + for _, secret := range []string{"TOPSECRETVALUE", "zzzbearer", "zzzcookie"} { + assert.NotContains(t, raw, secret) + } + + got := map[string]any{} + + for _, r := range res.Inputs { + got[*r.Path] = r.Value + } + + assert.Len(t, got, 5, "every expression is still traced") + assert.InDelta(t, 3, got["inputs.ok"], 0, "a plain expression keeps its value") +} + +func TestLogicRunBodyBudget(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + body := strings.Repeat("x", 200<<10) + backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(backend.Close) + + items := make([]any, 40) + for i := range items { + items[i] = i + } + + s.create(t, "loop", logicDef(requestTrigger(nil), la{"Loop": la{ + "type": "Foreach", "foreach": items, "operationOptions": "Sequential", "runAfter": la{}, + "actions": la{"Call": la{ + "type": "Http", "runAfter": la{}, + "inputs": la{"method": "GET", "uri": backend.URL, "retryPolicy": la{"type": "none"}}, + }}, + }})) + s.invoke(t, "loop", `{}`) + + run := s.latestRunName(t, "loop") + rc := s.factory.NewWorkflowRunActionRepetitionsRequestHistoriesClient() + calls, bodies := 0, 0 + + var names []string + + for pager := s.factory.NewWorkflowRunActionRepetitionsClient(). + NewListPager(logicRG, "loop", run, "Call", nil); pager.More(); { + page, err := pager.NextPage(t.Context()) + require.NoError(t, err) + + for _, rep := range page.Value { + names = append(names, *rep.Name) + } + } + + require.Len(t, names, len(items)) + + for _, name := range names { + page, lerr := rc.NewListPager(logicRG, "loop", run, "Call", name, nil).NextPage(t.Context()) + require.NoError(t, lerr) + + for _, h := range page.Value { + calls++ + + if h.Properties.Response.BodyLink != nil { + bodies++ + } + } + } + + assert.Equal(t, len(items), calls, "every call is still recorded") + assert.Positive(t, bodies) + assert.LessOrEqual(t, bodies*len(body), 4<<20, "the stored bodies of one run are bounded") +} diff --git a/services/azurearm/logic_swagger_test.go b/services/azurearm/logic_swagger_test.go new file mode 100644 index 0000000000..7f591f7a5c --- /dev/null +++ b/services/azurearm/logic_swagger_test.go @@ -0,0 +1,111 @@ +package azurearm_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestLogicListSwagger(t *testing.T) { + t.Parallel() + + schema := la{"type": "object", "properties": la{"name": la{"type": "string"}}} + + tests := []struct { + triggers la + name string + wantPath string + wantVerb string + wantPrm []string + wantBody bool + none bool + }{ + { + name: "post with schema", + triggers: la{"manual": la{ + "type": "Request", "kind": "Http", "inputs": la{"method": "POST", "schema": schema}, + }}, + wantPath: "/triggers/manual/paths/invoke", wantVerb: "post", wantBody: true, + }, + { + name: "relative path parameters", + triggers: la{"manual": la{ + "type": "Request", "kind": "Http", + "inputs": la{"method": "GET", "relativePath": "/items/{id}/parts/{part}", "schema": schema}, + }}, + wantPath: "/triggers/manual/paths/invoke/items/{id}/parts/{part}", wantVerb: "get", + wantPrm: []string{"id", "part"}, + }, + { + name: "default method is post", + triggers: la{"manual": la{ + "type": "Request", "kind": "Http", "inputs": la{}, + }}, + wantPath: "/triggers/manual/paths/invoke", wantVerb: "post", + }, + { + name: "no request trigger", + triggers: la{"tick": la{ + "type": "Recurrence", "recurrence": la{"frequency": "Day", "interval": 1}, + }}, + none: true, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + s.create(t, "api", logicDef(tc.triggers, la{})) + + res, err := s.factory.NewWorkflowsClient().ListSwagger(t.Context(), logicRG, "api", nil) + require.NoError(t, err) + + doc, ok := res.Interface.(map[string]any) + require.True(t, ok) + assert.Equal(t, "2.0", doc["swagger"]) + + paths, _ := doc["paths"].(map[string]any) + if tc.none { + assert.Empty(t, paths) + + return + } + + item, _ := paths[tc.wantPath].(map[string]any) + require.NotNil(t, item, "paths: %v", paths) + + op, _ := item[tc.wantVerb].(map[string]any) + require.NotNil(t, op) + + var path, query []string + + hasBody := false + + for _, p := range op["parameters"].([]any) { + pm, _ := p.(map[string]any) + + switch pm["in"] { + case "path": + path = append(path, pm["name"].(string)) + case "query": + query = append(query, pm["name"].(string)) + case "body": + hasBody = true + + assert.Equal(t, schema, pm["schema"]) + } + } + + assert.Equal(t, tc.wantPrm, path) + assert.Equal(t, []string{"api-version", "sp", "sv", "sig"}, query) + assert.Equal(t, tc.wantBody, hasBody) + }) + } + + s := newLogicStack(t) + _, err := s.factory.NewWorkflowsClient().ListSwagger(t.Context(), logicRG, "missing", nil) + require.Error(t, err) +} diff --git a/services/azurearm/logic_webhook_test.go b/services/azurearm/logic_webhook_test.go new file mode 100644 index 0000000000..18cc1b8147 --- /dev/null +++ b/services/azurearm/logic_webhook_test.go @@ -0,0 +1,257 @@ +package azurearm_test + +import ( + "encoding/json/v2" + "io" + "net/http" + "net/http/httptest" + "sync" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/logic/armlogic" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +type hookCall struct { + path, callback string +} + +type hookBackend struct { + calls []hookCall + status int + mu sync.Mutex +} + +func (b *hookBackend) ServeHTTP(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + + var body map[string]any + _ = json.Unmarshal(raw, &body, jsonx.V1()) + + cb, _ := body["callback"].(string) + + b.mu.Lock() + b.calls = append(b.calls, hookCall{path: r.URL.Path, callback: cb}) + status := b.status + b.mu.Unlock() + + if status != 0 { + w.WriteHeader(status) + } +} + +func (b *hookBackend) seen() []hookCall { + b.mu.Lock() + defer b.mu.Unlock() + + return append([]hookCall(nil), b.calls...) +} + +func (b *hookBackend) paths() []string { + calls := b.seen() + out := make([]string, 0, len(calls)) + + for _, c := range calls { + out = append(out, c.path) + } + + return out +} + +func webhookDef(uri string, subExtra string) la { + call := func(path string) la { + return la{ + "method": "POST", "uri": uri + path + subExtra, "body": la{"callback": "@{listCallbackUrl()}"}, + "retryPolicy": la{"type": "none"}, + } + } + + return logicDef(la{"hook": la{ + "type": "HttpWebhook", "inputs": la{"subscribe": call("/sub"), "unsubscribe": call("/unsub")}, + }}, la{"Mark": compose("@triggerBody()", nil)}) +} + +func TestLogicHTTPWebhookLifecycle(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &hookBackend{} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + wc := s.factory.NewWorkflowsClient() + s.create(t, "hooked", webhookDef(srv.URL, "")) + s.waitRuns(t) + + calls := b.seen() + require.Len(t, calls, 1) + assert.Equal(t, "/sub", calls[0].path) + + callback := calls[0].callback + require.Contains(t, callback, s.url+"/_logic/workflows/") + + res, err := s.factory.NewWorkflowTriggersClient().ListCallbackURL(t.Context(), logicRG, "hooked", "hook", nil) + require.NoError(t, err) + assert.Equal(t, callback, *res.Value, "listCallbackUrl() is the trigger's signed callback URL") + + code, _, _ := s.post(t, callback, `{"event":"x"}`) + require.Equal(t, http.StatusAccepted, code) + s.waitRuns(t) + + run := s.latestRun(t, "hooked") + assert.Equal(t, "hook", *run.Properties.Trigger.Name) + + out, _ := s.content(t, run.Properties.Trigger.OutputsLink).(map[string]any) + assert.Equal(t, map[string]any{"event": "x"}, out["body"]) + + code, _, _ = s.post(t, callback+"0", `{}`) + assert.Equal(t, http.StatusUnauthorized, code, "a tampered signature is refused") + + _, err = wc.Disable(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub"}, b.paths()) + assert.Equal(t, callback, b.seen()[1].callback) + + _, err = wc.Enable(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub", "/sub"}, b.paths()) + + _, err = wc.Delete(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub", "/sub", "/unsub"}, b.paths()) +} + +func TestLogicHTTPWebhookDefinitionChange(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &hookBackend{} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "hooked", webhookDef(srv.URL, "")) + s.waitRuns(t) + s.create(t, "hooked", webhookDef(srv.URL, "")) + s.waitRuns(t) + assert.Equal(t, []string{"/sub"}, b.paths(), "an unchanged definition does not resubscribe") + + s.create(t, "hooked", webhookDef(srv.URL, "?v=2")) + s.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub", "/sub"}, b.paths(), "a changed subscribe call replaces the subscription") + + s.create(t, "hooked", logicDef(requestTrigger(nil), la{"Mark": compose("1", nil)})) + s.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub", "/sub", "/unsub"}, b.paths(), "removing the trigger unsubscribes") +} + +func TestLogicHTTPWebhookSubscribeFailures(t *testing.T) { + t.Parallel() + + tests := []struct { + uri func(srv *httptest.Server) string + name string + status int + }{ + { + name: "backend error", + uri: func(s *httptest.Server) string { return s.URL }, + status: http.StatusInternalServerError, + }, + {name: "external host refused", uri: func(*httptest.Server) string { return "http://203.0.113.9" }}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + b := &hookBackend{status: tc.status} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + s.create(t, "hooked", webhookDef(tc.uri(srv), "")) + s.waitRuns(t) + + page, err := s.factory.NewWorkflowTriggerHistoriesClient().NewListPager(logicRG, "hooked", "hook", nil). + NextPage(t.Context()) + require.NoError(t, err) + require.Len(t, page.Value, 1) + assert.Equal(t, armlogic.WorkflowStatusFailed, *page.Value[0].Properties.Status) + + _, err = s.factory.NewWorkflowsClient().Delete(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + s.waitRuns(t) + + for _, p := range b.paths() { + assert.NotEqual(t, "/unsub", p, "no unsubscribe without a subscription") + } + }) + } +} + +func TestLogicHTTPWebhookValidation(t *testing.T) { + t.Parallel() + + s := newLogicStack(t) + + tests := []struct { + inputs la + name string + }{ + {name: "no subscribe", inputs: la{}}, + {name: "subscribe without uri", inputs: la{"subscribe": la{"method": "POST"}}}, + {name: "bad unsubscribe", inputs: la{ + "subscribe": la{ + "method": "POST", + "uri": "http://x", + }, + "unsubscribe": la{"method": "FETCH", "uri": "http://x"}, + }}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + _, err := s.factory.NewWorkflowsClient().CreateOrUpdate(t.Context(), logicRG, "badhook", + armlogic.Workflow{ + Location: new("westus"), + Properties: &armlogic.WorkflowProperties{ + Definition: logicDef( + la{"hook": la{"type": "HttpWebhook", "inputs": tc.inputs}}, la{}), + }, + }, nil) + require.Error(t, err) + assert.Contains(t, err.Error(), "InvalidTemplate") + }) + } +} + +func TestLogicHTTPWebhookPersistence(t *testing.T) { + t.Parallel() + + a := newLogicStack(t) + b := &hookBackend{} + srv := httptest.NewServer(b) + t.Cleanup(srv.Close) + + a.create(t, "hooked", webhookDef(srv.URL, "")) + a.waitRuns(t) + require.Equal(t, []string{"/sub"}, b.paths()) + + c := newLogicStack(t) + require.NoError(t, c.handler.Restore(t.Context(), a.handler.Snapshot(t.Context()))) + c.waitRuns(t) + assert.Equal(t, []string{"/sub"}, b.paths(), "a restored subscription is not repeated") + + _, err := c.factory.NewWorkflowsClient().Delete(t.Context(), logicRG, "hooked", nil) + require.NoError(t, err) + c.waitRuns(t) + assert.Equal(t, []string{"/sub", "/unsub"}, b.paths(), "the persisted subscription is unsubscribed on delete") +} diff --git a/services/azurearm/rp_apim.go b/services/azurearm/rp_apim.go index d9f28ffda0..220dd2fb6f 100644 --- a/services/azurearm/rp_apim.go +++ b/services/azurearm/rp_apim.go @@ -2,6 +2,7 @@ package azurearm import ( "context" + "crypto/x509" "encoding/base64" "encoding/binary" "errors" @@ -137,6 +138,14 @@ type APIMProvider struct { svcs map[string]*apimService ops map[string]*apimOp limiter *apimLimiter + quotas *apimQuotaStore + cache *apimCache + jwks *apimJWKS + bg *apimBG + certClients *apimCertClients + rootCAs *x509.CertPool + oneWay chan struct{} + wsSlots chan struct{} client *http.Client fastActivate time.Duration classicActive time.Duration @@ -146,8 +155,20 @@ type APIMProvider struct { // NewAPIMProvider creates an APIMProvider. func NewAPIMProvider() *APIMProvider { p := &APIMProvider{ - now: time.Now, mu: lockmetrics.New("azurearm.apim"), svcs: map[string]*apimService{}, ops: map[string]*apimOp{}, - limiter: newAPIMLimiter(), fastActivate: apimActivateFast, classicActive: apimActivateClassic, + now: time.Now, + mu: lockmetrics.New("azurearm.apim"), + svcs: map[string]*apimService{}, + ops: map[string]*apimOp{}, + limiter: newAPIMLimiter(), + quotas: newAPIMQuotaStore(), + cache: newAPIMCache(), + jwks: newAPIMJWKS(), + bg: newAPIMBG(), + certClients: newAPIMCertClients(), + oneWay: make(chan struct{}, apimMaxOneWay), + wsSlots: make(chan struct{}, apimWSMaxSessions), + fastActivate: apimActivateFast, + classicActive: apimActivateClassic, } p.client = p.newBackendClient() @@ -610,6 +631,10 @@ func (p *APIMProvider) writeService( next.applyEnvelope(body) next.bump() + if prev == nil { + seedAPIMBuiltins(next, now) + } + switch { case prev == nil: next.Transition, next.ReadyAt = apimStateActivating, now.Add(p.activation(next.SKU)) @@ -703,11 +728,16 @@ func (p *APIMProvider) ListKeys(context.Context, ResourceID) (map[string]any, er // Reset implements ResourceProvider. func (p *APIMProvider) Reset() { + p.bg.stop(false) p.mu.Lock(apimCReset) p.svcs = map[string]*apimService{} p.ops = map[string]*apimOp{} p.mu.Unlock() p.limiter.reset() + p.quotas.reset() + p.cache.reset() + p.jwks.reset() + p.certClients.reset() } // DeleteResourcesInGroup implements ResourceProvider. diff --git a/services/azurearm/rp_apim_bg.go b/services/azurearm/rp_apim_bg.go new file mode 100644 index 0000000000..e0b2f78934 --- /dev/null +++ b/services/azurearm/rp_apim_bg.go @@ -0,0 +1,88 @@ +package azurearm + +import ( + "context" + "time" + + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" +) + +const apimBGStopWait = 10 * time.Second + +// apimBG tracks the gateway's long-lived work, WebSocket sessions and one-way requests, so that Reset and Close +// can cancel it and wait for it. +type apimBG struct { + mu *lockmetrics.RWMutex + live map[uint64]apimBGUnit + next uint64 + closed bool +} + +type apimBGUnit struct { + cancel context.CancelFunc + done chan struct{} +} + +func newAPIMBG() *apimBG { + return &apimBG{mu: lockmetrics.New("azurearm.apim.bg"), live: map[uint64]apimBGUnit{}} +} + +// begin registers a unit of work; it reports false once the provider is closed. +func (b *apimBG) begin(cancel context.CancelFunc) (uint64, bool) { + b.mu.Lock("begin") + defer b.mu.Unlock() + + if b.closed { + return 0, false + } + + b.next++ + b.live[b.next] = apimBGUnit{cancel: cancel, done: make(chan struct{})} + + return b.next, true +} + +func (b *apimBG) end(id uint64) { + b.mu.Lock("end") + + if u, ok := b.live[id]; ok { + delete(b.live, id) + close(u.done) + } + + b.mu.Unlock() +} + +// stop cancels all registered work and waits for it, bounded; final also refuses new work. +func (b *apimBG) stop(final bool) { + b.mu.Lock("stop") + + if final { + b.closed = true + } + + units := make([]apimBGUnit, 0, len(b.live)) + for _, u := range b.live { + units = append(units, u) + } + + b.mu.Unlock() + + deadline := time.NewTimer(apimBGStopWait) + defer deadline.Stop() + + for _, u := range units { + u.cancel() + } + + for _, u := range units { + select { + case <-u.done: + case <-deadline.C: + return + } + } +} + +// Close cancels every open WebSocket session and in-flight one-way request and refuses new ones. +func (p *APIMProvider) Close() { p.bg.stop(true) } diff --git a/services/azurearm/rp_apim_cache.go b/services/azurearm/rp_apim_cache.go new file mode 100644 index 0000000000..6d4746e5be --- /dev/null +++ b/services/azurearm/rp_apim_cache.go @@ -0,0 +1,200 @@ +package azurearm + +import ( + "bytes" + "io" + "net/http" + "net/textproto" + "slices" + "strconv" + "strings" + "time" +) + +const ( + apimCCacheLookup = "cache-lookup" + apimCCacheStore = "cache-store" + apimCCacheLookupValue = "cache-lookup-value" + apimCCacheStoreValue = "cache-store-value" + apimCCacheRemoveValue = "cache-remove-value" + apimCVaryHeader = "vary-by-header" + apimCVaryQuery = "vary-by-query-parameter" + apimCCachingType = "caching-type" + apimCDownstream = "downstream-caching-type" + apimCKey = "key" + apimCVariableName = "variable-name" + apimCDefaultValue = "default-value" + apimCDuration = "duration" +) + +// apimUncacheableHeaders are per-client or per-connection headers; the docs are silent, so a cached response +// never replays them to another client (emulator choice). +func apimUncacheableHeaders() []string { + return []string{ + "Set-Cookie", "Set-Cookie2", "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Te", + "Trailer", "Transfer-Encoding", "Upgrade", + } +} + +type gwCacheKey struct { + lookup *polNode + key string +} + +func (g *gwState) cacheLookup(n *polNode) { + if g.r.Method != http.MethodGet { + return + } + + if g.header.Get(apimCAuthorizationX) != "" && !g.boolAttr(n, "allow-private-response-caching", false) { + return + } + + parts := []string{g.plan.svcKey, "resp", strings.ToLower(hostFromHostHeader(g.r.Host)), g.plan.path} + + if g.boolAttr(n, "vary-by-developer", false) { + parts = append(parts, "dev", g.plan.ownerID) + } + + if g.boolAttr(n, "vary-by-developer-groups", false) { + parts = append(parts, "grp", strings.Join(g.plan.groups, ",")) + } + + for _, h := range n.values(apimCVaryHeader) { + parts = append( + parts, + "h:"+strings.ToLower(h), + strings.Join(g.header.Values(textproto.CanonicalMIMEHeaderKey(h)), ","), + ) + } + + for _, q := range n.values(apimCVaryQuery) { + parts = append(parts, "q:"+q, strings.Join(g.query[q], ",")) + } + + if g.evalErr != nil { + return + } + + key := apimKeyOf(parts...) + g.cacheKey = &gwCacheKey{key: key, lookup: n} + + v, expires, ok := g.p.cache.get(key, g.now()) + if !ok { + return + } + + cr, isResp := v.(*gwCachedResponse) + if !isResp { + return + } + + h := http.Header{} + for k, vals := range cr.header { + h[k] = slices.Clone(vals) + } + + g.setResponse(cr.status, h, cr.body) + g.cacheHit = true + g.downstream(n, expires.Sub(g.now())) +} + +func (g *gwState) downstream(lookup *polNode, ttl time.Duration) { + kind := g.sub(lookup.Attrs[apimCDownstream]) + + if kind != "private" && kind != "public" { + return + } + + cc := kind + ", max-age=" + strconv.Itoa(max(0, int(ttl.Seconds()))) + if g.boolAttr(lookup, "must-revalidate", true) { + cc += ", must-revalidate" + } + + g.respHeader.Set("Cache-Control", cc) +} + +func (g *gwState) cacheStore(n *polNode) { + if g.cacheKey == nil || g.cacheHit { + return + } + + secs := g.intAttr(n, apimCDuration, 0) + any200 := g.boolAttr(n, "cache-response", false) + + if g.evalErr != nil || secs <= 0 || (g.status != http.StatusOK && !any200) || g.respBody == nil { + return + } + + body, err := io.ReadAll(io.LimitReader(g.respBody, apimMaxCacheEntry+1)) + if err != nil { + return + } + + if len(body) > apimMaxCacheEntry { + g.respBody = &gwJoinedBody{Reader: io.MultiReader(bytes.NewReader(body), g.respBody), c: g.respBody} + + return + } + + _ = g.respBody.Close() + g.respBody = io.NopCloser(bytes.NewReader(body)) + + h := http.Header{} + + for k, v := range g.respHeader { + if !slices.Contains(apimUncacheableHeaders(), k) { + h[k] = slices.Clone(v) + } + } + + ttl := time.Duration(secs) * time.Second + g.p.cache.put(g.cacheKey.key, &gwCachedResponse{status: g.status, header: h, body: body}, len(body), ttl, g.now()) + g.downstream(g.cacheKey.lookup, ttl) +} + +type gwJoinedBody struct { + io.Reader + + c io.Closer +} + +func (b *gwJoinedBody) Close() error { return b.c.Close() } + +func (g *gwState) cacheValue(n *polNode) { + key := g.sub(n.Attrs[apimCKey]) + if g.evalErr != nil { + return + } + + if len(key) > apimMaxCounterKey { + g.evalErr = apimExprFail("the key is longer than %d characters", apimMaxCounterKey) + + return + } + + full := apimKeyOf(g.plan.svcKey, "val", key) + + switch n.Name { + case apimCCacheLookupValue: + name := n.Attrs[apimCVariableName] + if v, _, ok := g.p.cache.get(full, g.now()); ok { + g.vars[name] = v + + return + } + + if d, has := n.Attrs[apimCDefaultValue]; has { + g.vars[name] = g.subVal(d) + } + case apimCCacheStoreValue: + v := g.subVal(n.Attrs[fieldValue]) + secs := g.intAttr(n, apimCDuration, 0) + + if g.evalErr == nil && secs > 0 { + g.p.cache.put(full, v, len(apimExprString(v)), time.Duration(secs)*time.Second, g.now()) + } + case apimCCacheRemoveValue: + g.p.cache.remove(full) + } +} diff --git a/services/azurearm/rp_apim_clientcert.go b/services/azurearm/rp_apim_clientcert.go new file mode 100644 index 0000000000..466bf81850 --- /dev/null +++ b/services/azurearm/rp_apim_clientcert.go @@ -0,0 +1,251 @@ +package azurearm + +import ( + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/hex" + "net/http" + "strings" + + "software.sslmate.com/src/go-pkcs12" + + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" +) + +const ( + apimCAuthCertificate = "authentication-certificate" + apimMaxCertClients = 64 +) + +// gwCert is the part of a stored certificate the gateway needs to present it or to read its public key. +type gwCert struct { + thumbprint string + data string + password string + spki string + hasKey bool +} + +func (s *apimService) certMap() map[string]gwCert { + ents := s.Generic[apimCertificatesType] + out := make(map[string]gwCert, len(ents)) + + for _, e := range ents { + hasKey, _ := e.Props["privateKey"].(bool) + out[strings.ToLower(e.ID)] = gwCert{ + thumbprint: strOf( + e.Props, + apimCThumbprint, + ), data: strOf(e.Props, "data"), password: strOf(e.Props, apimCPasswordAttr), + spki: strOf(e.Props, "publicKey"), hasKey: hasKey, + } + } + + return out +} + +func (c gwCert) tlsCert() (tls.Certificate, bool) { + raw, err := base64.StdEncoding.DecodeString(c.data) + if err != nil { + return tls.Certificate{}, false + } + + return apimTLSFromPFX(raw, c.password) +} + +func apimTLSFromPFX(raw []byte, password string) (tls.Certificate, bool) { + key, cert, chain, err := pkcs12.DecodeChain(raw, password) + if err != nil || cert == nil || key == nil { + return tls.Certificate{}, false + } + + out := tls.Certificate{Certificate: [][]byte{cert.Raw}, PrivateKey: key, Leaf: cert} + for _, c := range chain { + out.Certificate = append(out.Certificate, c.Raw) + } + + return out, true +} + +// apimCertClients caches one HTTP client per client certificate, each cloned from the gateway's own transport so +// the loopback dial policy stays in force. +type apimCertClients struct { + mu *lockmetrics.RWMutex + m map[string]*http.Client +} + +func newAPIMCertClients() *apimCertClients { + return &apimCertClients{mu: lockmetrics.New("azurearm.apim.certclients"), m: map[string]*http.Client{}} +} + +func (c *apimCertClients) reset() { + c.mu.Lock("reset") + c.m = map[string]*http.Client{} + c.mu.Unlock() +} + +// SetBackendRootCAs adds trust anchors for https backends; call it before the gateway serves traffic. +func (p *APIMProvider) SetBackendRootCAs(pool *x509.CertPool) { + p.rootCAs = pool + p.client = p.newBackendClient() + p.certClients.reset() +} + +func (p *APIMProvider) clientWithCert(key string, cert tls.Certificate) *http.Client { + p.certClients.mu.Lock("clientWithCert") + defer p.certClients.mu.Unlock() + + if c, ok := p.certClients.m[key]; ok { + return c + } + + if len(p.certClients.m) >= apimMaxCertClients { + for k, c := range p.certClients.m { + c.CloseIdleConnections() + delete(p.certClients.m, k) + + break + } + } + + base, _ := p.client.Transport.(*http.Transport) + tr := base.Clone() + + cfg := &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: p.rootCAs} + if tr.TLSClientConfig != nil { + cfg = tr.TLSClientConfig.Clone() + cfg.MinVersion = max(cfg.MinVersion, tls.VersionTLS12) + } + + cfg.Certificates = []tls.Certificate{cert} + tr.TLSClientConfig = cfg + + c := &http.Client{Transport: tr, CheckRedirect: p.client.CheckRedirect} + p.certClients.m[key] = c + + return c +} + +// authCert resolves the client certificate of an authentication-certificate statement. +func (g *gwState) authCert(n *polNode) { + var ( + cert tls.Certificate + ok bool + key string + ) + + switch { + case n.Attrs[apimCBodyAttr] != "": + raw, err := base64.StdEncoding.DecodeString(g.sub(n.Attrs[apimCBodyAttr])) + pw := g.sub(n.Attrs[apimCPasswordAttr]) + + if err == nil { + cert, ok = apimTLSFromPFX(raw, pw) + } + + sum := sha256.Sum256(append(append(raw, 0), pw...)) + key = apimKeyOf(g.plan.svcKey, apimCBodyAttr, hex.EncodeToString(sum[:])) + case n.Attrs[apimCCertID] != "": + c, found := g.plan.certs[strings.ToLower(g.sub(n.Attrs[apimCCertID]))] + if found && c.hasKey { + cert, ok = c.tlsCert() + } + + key = apimKeyOf(g.plan.svcKey, "id", c.thumbprint) + default: + th := strings.ToUpper(g.sub(n.Attrs[apimCThumbprint])) + + for _, c := range g.plan.certs { + if c.thumbprint == th && c.hasKey { + cert, ok = c.tlsCert() + } + } + + key = apimKeyOf(g.plan.svcKey, "id", th) + } + + if !ok { + g.failR(http.StatusInternalServerError, "ClientCertificateNotFound", + "The client certificate for authentication-certificate could not be loaded.") + + return + } + + g.client = g.p.clientWithCert(key, cert) +} + +func validateAuthCert(s *apimService, n *polNode) error { + count := 0 + + for _, a := range []string{apimCThumbprint, apimCCertID, apimCBodyAttr} { + if n.Attrs[a] != "" { + count++ + } + } + + if count != 1 { + return polErr(n, "Exactly one of thumbprint, certificate-id and body is required.") + } + + if n.Attrs[apimCBodyAttr] != "" && n.Attrs[apimCPasswordAttr] == "" { + return polErr(n, "The password is required with body.") + } + + for _, a := range []string{apimCThumbprint, apimCCertID} { + v := n.Attrs[a] + if _, expr, _ := apimIsExprText(v); expr || v == "" { + continue + } + + if !s.hasClientCert(a, v) { + return polErr(n, "No uploaded certificate with a private key matches '%s'.", v) + } + } + + return nil +} + +func (s *apimService) hasClientCert(attr, v string) bool { + for _, e := range s.Generic[apimCertificatesType] { + hasKey, _ := e.Props["privateKey"].(bool) + if !hasKey { + continue + } + + if (attr == apimCCertID && strings.EqualFold(e.ID, v)) || + (attr == apimCThumbprint && strings.EqualFold(strOf(e.Props, apimCThumbprint), v)) { + return true + } + } + + return false +} + +func (g *gwState) httpClient() *http.Client { + if g.client != nil { + return g.client + } + + return g.p.client +} + +// sendClient is the client of a send-request, using its own authentication-certificate child when present. +func (g *gwState) sendClient(n *polNode) *http.Client { + if ac := n.kid(apimCAuthCertificate); ac != nil { + saved := g.client + g.authCert(ac) + + c := g.client + g.client = saved + + if c == nil { + return g.p.client + } + + return c + } + + return g.p.client +} diff --git a/services/azurearm/rp_apim_consts.go b/services/azurearm/rp_apim_consts.go index 3eb4ce1c81..329aa02cb0 100644 --- a/services/azurearm/rp_apim_consts.go +++ b/services/azurearm/rp_apim_consts.go @@ -1,6 +1,8 @@ package azurearm const ( + apimCRequired = "required" + apimMethodGet = "get" apimCAPI = "API" apimCAccessControlRequestMethod = "Access-Control-Request-Method" apimOpenAPI2 = "2.0" diff --git a/services/azurearm/rp_apim_do.go b/services/azurearm/rp_apim_do.go index 02ccab6621..f334f7a8a9 100644 --- a/services/azurearm/rp_apim_do.go +++ b/services/azurearm/rp_apim_do.go @@ -73,7 +73,7 @@ func apimKinds() []apimKind { func apiKind() apimKind { return apimKind{ - typ: apimCApis, norm: normAPI, del: delAPI, + typ: apimCApis, norm: normAPI, del: delAPI, view: dropSecrets(apimRevCreated, apimRevUpdated), store: func(s *apimService) map[string]*apimEntity { return s.APIs }, } } @@ -94,7 +94,7 @@ func productKind() apimKind { func subKind() apimKind { return apimKind{ - typ: sbSubscriptionsType, norm: normSubscription, view: viewSubscription, + typ: sbSubscriptionsType, norm: normSubscription, view: viewSubscription, del: delBuiltinSub, store: func(s *apimService) map[string]*apimEntity { return s.Subs }, } } @@ -198,15 +198,7 @@ func (p *APIMProvider) route(s *apimService, req apimReq) (apimResp, error) { case apimCPolicies: return p.scoped(s, req, policyKind(apimCPolicies), "", 0) case apimCProducts: - if len(r) >= apimProductAPIsLen && strings.EqualFold(r[2], apimCApis) { - return p.productAPIs(s, req) - } - - if len(r) >= apimLinkMinSegs && strings.EqualFold(r[2], apimGroupsType) { - return p.linked(s, req, apimProductGroupLink()) - } - - return p.collection(s, req, productKind(), "", 0) + return p.routeProduct(s, req) case sbSubscriptionsType: return p.collection(s, req, subKind(), "", 0) case "namedvalues": @@ -243,10 +235,16 @@ func (p *APIMProvider) routeAPI(s *apimService, req apimReq) (apimResp, error) { ) case strings.EqualFold(r[2], nsOperations): return p.collection(s, req, opKind(), r[1], apimAPIChildIdx) + case strings.EqualFold(r[2], "revisions") && len(r) == apimAPIChildLen: + return p.apiRevisionList(s, req) case strings.EqualFold(r[2], apimCPolicies): return p.scoped(s, req, policyKind("apis/policies"), "apis/"+r[1], apimAPIChildIdx) } + if k, ok := apiChildKind(r[2]); ok { + return p.collection(s, req, k, r[1], apimAPIChildIdx) + } + return p.collection(s, req, apiKind(), "", 0) } @@ -312,6 +310,12 @@ func (p *APIMProvider) scoped(s *apimService, req apimReq, k apimKind, scope str } func (p *APIMProvider) policyScopeExists(s *apimService, r []string) error { + if len(r) >= 2 && strings.EqualFold(r[0], apimCProducts) { + if _, ok := s.Products[entKey("", r[1])]; !ok { + return apimNotFound(apimScopeProduct) + } + } + if len(r) >= 2 && strings.EqualFold(r[0], apimCApis) { if _, ok := s.APIs[entKey("", r[1])]; !ok { return apimNotFound(apimCAPI) @@ -600,3 +604,32 @@ func withProp(props map[string]any, k string, v any) map[string]any { return out } + +func (p *APIMProvider) routeProduct(s *apimService, req apimReq) (apimResp, error) { + r := req.Rest + + switch { + case len(r) >= apimProductAPIsLen && strings.EqualFold(r[2], apimCApis): + return p.productAPIs(s, req) + case len(r) >= apimLinkMinSegs && strings.EqualFold(r[2], apimGroupsType): + return p.linked(s, req, apimProductGroupLink()) + case len(r) >= apimLinkMinSegs && strings.EqualFold(r[2], apimCPolicies): + return p.scoped(s, req, policyKind("products/policies"), "products/"+r[1], apimProductPolicyIdx) + } + + return p.collection(s, req, productKind(), "", 0) +} + +// apiChildKind maps the collection segment under an API to its entity kind. +func apiChildKind(seg string) (apimKind, bool) { + switch strings.ToLower(seg) { + case apimDiagnosticsType: + return apimMgmtKind(apimAPIDiagType), true + case "schemas": + return apimMgmtKind(apimAPISchemasType), true + case "releases": + return apimMgmtKind(apimAPIReleasesType), true + } + + return apimKind{}, false +} diff --git a/services/azurearm/rp_apim_entities.go b/services/azurearm/rp_apim_entities.go index 9f5fab1a34..95a7b78adf 100644 --- a/services/azurearm/rp_apim_entities.go +++ b/services/azurearm/rp_apim_entities.go @@ -102,7 +102,7 @@ func canonicalTemplate(tpl string) string { return apimTemplateRE.ReplaceAllString(path, "{}") } -func normAPI(s *apimService, _, id string, in map[string]any, _ *apimEntity) (map[string]any, error) { +func normAPI(s *apimService, _, id string, in map[string]any, prev *apimEntity) (map[string]any, error) { out := cloneAnyMap(in) var imported []apimImportedOp @@ -130,15 +130,21 @@ func normAPI(s *apimService, _, id string, in map[string]any, _ *apimEntity) (ma out["isOnline"] = true - cur, err := optBool(out, "isCurrent", true) + rev, isRev, err := apiRevisionOf(id) if err != nil { return nil, err } - out["isCurrent"] = cur + out[apimRevision], out[apimCurrent] = rev, !isRev + stamp := apimNow(s).UTC().Format(time.RFC3339) + out[apimRevCreated], out[apimRevUpdated] = stamp, stamp - if _, has := out["apiRevision"]; !has { - out["apiRevision"] = "1" + if prev != nil { + out[apimCurrent], out[apimRevCreated] = prev.Props[apimCurrent], prev.Props[apimRevCreated] + } + + if isRev && s.APIs[entKey("", apiBaseID(id))] == nil { + return nil, apimInvalid("The revision '%s' needs the existing API '%s'.", id, apiBaseID(id)) } if len(imported) > 0 { @@ -172,7 +178,8 @@ func apiFields(s *apimService, id string, in, out map[string]any) error { out[apimCPath] = path for _, other := range s.APIs { - if !strings.EqualFold(other.ID, id) && strings.EqualFold(strOf(other.Props, apimCPath), path) { + if !strings.EqualFold(apiBaseID(other.ID), apiBaseID(id)) && + strings.EqualFold(strOf(other.Props, apimCPath), path) { return apimInvalid("The API path %q is already used by another API.", path) } } @@ -269,6 +276,14 @@ func delAPI(s *apimService, _, id string, _ url.Values) error { delete(s.Policies, entKey("apis/"+lid, apimPolicyID)) + for _, typ := range []string{apimAPIDiagType, apimAPISchemasType, apimAPIReleasesType} { + for k, e := range s.Generic[typ] { + if strings.EqualFold(e.Parent, id) { + delete(s.Generic[typ], k) + } + } + } + for k := range s.ProductAPIs { if strings.HasSuffix(k, "/"+lid) { delete(s.ProductAPIs, k) @@ -329,7 +344,7 @@ func opParams(in map[string]any, tpl string) ([]any, error) { for _, name := range inTpl { if !declared[name] { - params = append(params, map[string]any{fieldName: name, "required": true, fieldType: "string"}) + params = append(params, map[string]any{fieldName: name, apimCRequired: true, fieldType: apxString}) } } @@ -451,6 +466,8 @@ func delProduct(s *apimService, _, id string, q url.Values) error { delete(s.Subs, k) } + delete(s.Policies, entKey("products/"+id, apimPolicyID)) + prefix := strings.ToLower(id) + "/" for k := range s.ProductAPIs { if strings.HasPrefix(k, prefix) { diff --git a/services/azurearm/rp_apim_exec.go b/services/azurearm/rp_apim_exec.go index bd41e4d3ac..79b32d4cd9 100644 --- a/services/azurearm/rp_apim_exec.go +++ b/services/azurearm/rp_apim_exec.go @@ -35,10 +35,27 @@ type gwState struct { backend *gwBackend cors *polNode cancel context.CancelFunc + vars map[string]any + lastErr *gwLastError + evalErr error + cacheKey *gwCacheKey + cur *polNode + seenKeys map[string]bool + client *http.Client + t0 time.Time rewrite string + path string + reqID string + section string + basicAuth string + deferred []func(written int64) + body []byte status int short bool noCopy bool + errored bool + cacheHit bool + wrote bool } func existsAction(m map[string][]string, key, action string, vals []string) { @@ -105,17 +122,17 @@ func (g *gwState) parseDocs() ([]*polNode, error) { return nil, err } + if err = g.inlineFragments(n); err != nil { + return nil, err + } + docs = append(docs, n) } return docs, nil } -func (g *gwState) sub(s string) string { - return apimNamedRefRE.ReplaceAllStringFunc(s, func(m string) string { - return g.plan.named[strings.ToLower(m[2:len(m)-2])] - }) -} +func (g *gwState) sub(s string) string { return apimExprString(g.subVal(s)) } func (g *gwState) subAll(in []string) []string { out := make([]string, len(in)) @@ -126,11 +143,7 @@ func (g *gwState) subAll(in []string) []string { return out } -func (g *gwState) fail(status int, msg string) { - body, _ := json.Marshal(map[string]any{apimCStatusCode: status, fieldMessage: msg}, jsonx.V1()) - g.setResponse(status, http.Header{apimCContentType: {"application/json"}}, body) - g.short = true -} +func (g *gwState) fail(status int, msg string) { g.failR(status, "", msg) } func (g *gwState) setResponse(status int, h http.Header, body []byte) { g.status, g.respHeader, g.respBody = status, h, io.NopCloser(bytes.NewReader(body)) @@ -165,39 +178,46 @@ func (g *gwState) run() { g.extra = http.Header{} g.header = g.r.Header.Clone() g.query = g.r.URL.Query() + g.vars = map[string]any{} + g.seenKeys = map[string]bool{} if su := strOf(g.plan.api, apimCServiceURL); su != "" { g.target, _ = url.Parse(su) } - for _, section := range []string{polInbound, polBackend} { - for _, n := range expandSection(docs, section) { - g.execRequest(n) + g.pipeline(docs) + g.finish() +} - if g.short { - g.finish() +func (g *gwState) pipeline(docs []*polNode) { + for _, section := range []string{polInbound, polBackend, polOutbound} { + if section == polBackend && g.cacheHit { + continue + } - return - } + if section == polOutbound && g.respBody == nil { + g.setResponse(http.StatusOK, http.Header{}, nil) } - } - if g.respBody == nil { - g.setResponse(http.StatusOK, http.Header{}, nil) - } + g.execList(expandSection(docs, section), section, "") - for _, n := range expandSection(docs, polOutbound) { - g.execResponse(n) + if g.errored { + g.onError(docs) + + return + } if g.short { - break + return } } - - g.finish() } func (g *gwState) finish() { + if g.wrote { + return + } + h := g.w.Header() for _, src := range []http.Header{g.respHeader, g.extra} { @@ -211,8 +231,14 @@ func (g *gwState) finish() { g.applyCORS(h) g.w.WriteHeader(g.status) + var written int64 + if g.respBody != nil && g.r.Method != http.MethodHead { - _, _ = io.Copy(g.w, g.respBody) + written, _ = io.Copy(g.w, g.respBody) + } + + for _, d := range g.deferred { + d(written) } } @@ -243,6 +269,27 @@ func (g *gwState) execRequest(n *polNode) { } case apimCForwardRequest: g.forward(n) + default: + g.execRequestExt(n) + } +} + +func (g *gwState) execRequestExt(n *polNode) { + switch n.Name { + case apimCRateLimitByKey: + g.rateLimitByKey(n) + case apimCQuota: + g.quota(n) + case apimCQuotaByKey: + g.quotaByKey(n) + case apimCValidateJWT: + g.validateJWT(n) + case apimCCacheLookup: + g.cacheLookup(n) + case apimCAuthBasic: + g.authBasic(n) + case apimCAuthCertificate: + g.authCert(n) } } @@ -267,6 +314,8 @@ func (g *gwState) execResponse(n *polNode) { if g.cors == nil { g.cors = n } + case apimCCacheStore: + g.cacheStore(n) } } @@ -393,7 +442,7 @@ func (g *gwState) rateLimit(n *polNode) { key := fmt.Sprintf("%s|%d:%d|%s", n.Scope, n.Line, n.Col, who) - ok, left, retry := g.p.limiter.take(key, calls, time.Duration(period)*time.Second, g.plan.now()) + ok, left, retry := g.p.limiter.take(key, calls, 1, time.Duration(period)*time.Second, g.plan.now()) if h := n.Attrs["total-calls-header-name"]; h != "" { g.extra.Set(h, strconv.Itoa(calls)) @@ -408,7 +457,7 @@ func (g *gwState) rateLimit(n *polNode) { } secs := strconv.Itoa(int(math.Ceil(retry.Seconds()))) - g.fail(http.StatusTooManyRequests, apimMsgRateLimit) + g.failR(http.StatusTooManyRequests, "RateLimitExceeded", apimMsgRateLimit) g.respHeader.Set(firstNonEmpty(n.Attrs["retry-after-header-name"], apimCRetryAfter), secs) } @@ -439,8 +488,13 @@ func (g *gwState) buildURL() (*url.URL, error) { return nil, errNoAPIMBackend } - if g.target.Scheme != acaScaleHTTP && g.target.Scheme != acaSchemeHTTPS { - return nil, errAPIMWebSocket + scheme := apimHTTPScheme(g.target.Scheme) + if scheme != acaScaleHTTP && scheme != acaSchemeHTTPS { + return nil, errAPIMNotUpgrade + } + + if scheme != g.target.Scheme && !apimIsWebSocket(g.r) { + return nil, errAPIMNotUpgrade } path, query := g.suffixPath(), g.query @@ -460,6 +514,7 @@ func (g *gwState) buildURL() (*url.URL, error) { } u := *g.target + u.Scheme = scheme u.Path = strings.TrimRight(g.target.Path, "/") + "/" + strings.TrimLeft(path, "/") u.RawPath = "" @@ -479,10 +534,7 @@ func fillTemplate(tpl string, params map[string]string) string { }) } -var ( - errNoAPIMBackend = errors.New("the API has no serviceUrl and no set-backend-service policy selected a backend") - errAPIMWebSocket = errors.New("WebSocket backends are not supported") -) +var errNoAPIMBackend = errors.New("the API has no serviceUrl and no set-backend-service policy selected a backend") func (g *gwState) forward(n *polNode) { u, err := g.buildURL() @@ -492,6 +544,12 @@ func (g *gwState) forward(n *polNode) { return } + if apimIsWebSocket(g.r) { + g.proxyWebSocket(u) + + return + } + timeout := apimForwardTimeout if t, convErr := strconv.Atoi(strings.TrimSpace(n.Attrs[apimCTimeout])); convErr == nil { timeout = time.Duration(t) * time.Second @@ -501,7 +559,7 @@ func (g *gwState) forward(n *polNode) { timeout = time.Duration(t) * time.Millisecond } - body, err := io.ReadAll(g.r.Body) + body, err := g.bodyBytes() if err != nil { g.fail(http.StatusRequestEntityTooLarge, "The request body is too large.") @@ -522,7 +580,11 @@ func (g *gwState) forward(n *polNode) { req.Header.Set(apimHeaderXForward, hostOnly(g.r.RemoteAddr)) g.applyCredentials(req) - resp, err := g.p.client.Do(req) //nolint:bodyclose // closed in close() + if g.basicAuth != "" { + req.Header.Set(apimCAuthorizationX, g.basicAuth) + } + + resp, err := g.httpClient().Do(req) //nolint:bodyclose // closed in close() if err != nil { g.upstreamError(err) @@ -535,16 +597,23 @@ func (g *gwState) forward(n *polNode) { } func (g *gwState) upstreamError(err error) { + if errors.Is(err, context.DeadlineExceeded) { + g.failR(http.StatusBadGateway, "Timeout", "The backend did not respond within the configured timeout.") + + return + } + if errors.Is(err, ErrAPIMDestinationNotPermitted) { - g.fail( + g.failR( http.StatusBadGateway, + "BackendConnectionFailure", "The backend host is outside loopback and external backends are not allowed (--azure-arm-apim-allow-external).", ) return } - g.fail(http.StatusBadGateway, "The backend request failed.") + g.failR(http.StatusBadGateway, "BackendConnectionFailure", "The backend request failed.") } func (g *gwState) applyCredentials(req *http.Request) { @@ -574,7 +643,7 @@ func copyForwardHeaders(dst, src http.Header) { for k, v := range src { switch k { case "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Proxy-Connection", "Te", - "Trailer", "Transfer-Encoding", "Upgrade", "Host", "Content-Length": + "Trailer", "Transfer-Encoding", "Upgrade", apxHost, "Content-Length": continue } diff --git a/services/azurearm/rp_apim_expr.go b/services/azurearm/rp_apim_expr.go new file mode 100644 index 0000000000..e6a4d61b5e --- /dev/null +++ b/services/azurearm/rp_apim_expr.go @@ -0,0 +1,1483 @@ +package azurearm + +import ( + "cmp" + "errors" + "fmt" + "regexp" + "slices" + "strconv" + "strings" + "time" + "unicode" + + "github.com/google/uuid" +) + +const ( + apxString = "string" + apxTrueLit = "true" + apxLong = "long" + apxScheme = "Scheme" + apxInt = "int" + apxNull = "null" + apxQueryString = "QueryString" + apxStartsWith = "StartsWith" + apxTrim = "Trim" + apimExprKeyDefault = 2 + apimExprGenericClose = 2 + apimExprGenericLen = 3 + apimExprMaxArgs = 8 + apimExprMaxLen = 4096 + apimExprMaxDepth = 32 + apimExprMaxNodes = 512 + apimExprMaxString = 1 << 20 + apimExprTrue = "True" + apimExprFalse = "False" +) + +var ( + errAPIMExprSyntax = errors.New("syntax error") + errAPIMExprRuntime = errors.New("expression evaluation failed") +) + +const ( + apxTypeBool = "bool" + apxVariables = "Variables" + apxUser = "User" + apxURL = "Url" + apxPort = "Port" + apxURLTemplate = "UrlTemplate" + apxOrdinalIC = "OrdinalIgnoreCase" + apxEndsWith = "EndsWith" + apxToString = "ToString" + apxContext = "context" + apxID = "Id" + apxHost = "Host" + apxAPI = "Api" + apxLastError = "LastError" + apxHeaders = "Headers" + apxName = "Name" + apxMessage = "Message" + apxLength = "Length" + apxBody = "Body" + apxContains = "Contains" + apxParse = "Parse" + apxDateTime = "DateTime" + apxRequest = "Request" + apxResponse = "Response" + apxSubscription = "Subscription" + apxProduct = "Product" + apxOperation = "Operation" + apxTimestamp = "Timestamp" + apxRequestID = "RequestId" + apxStatusCode = "StatusCode" + apxStatusReason = "StatusReason" + apxPath = "Path" + apxMethod = "Method" + apxSource = "Source" + apxReason = "Reason" + apxScope = "Scope" + apxSection = "Section" + apxPolicyID = "PolicyId" + apxIPAddress = "IpAddress" + apxMatchedParameters = "MatchedParameters" + apxOriginalURL = "OriginalUrl" + apxQuery = "Query" + apxSecond = "Second" +) + +type apimExprNode struct { + val any + name string + op string + typ string + args []*apimExprNode + kind byte + opt bool +} + +const ( + nLit byte = iota + nIdent + nMember + nCall + nIndex + nUnary + nBinary + nTernary + nCast +) + +type apimExprTok struct { + val any + text string + kind byte +} + +const ( + tIdent byte = iota + tInt + tStr + tOp + tEOF +) + +func apimExprLex(src string) ([]apimExprTok, error) { + var toks []apimExprTok + + rs := []rune(src) + + for i := 0; i < len(rs); { + if unicode.IsSpace(rs[i]) { + i++ + + continue + } + + tok, next, err := apimExprLexTok(rs, i) + if err != nil { + return nil, err + } + + if toks = append(toks, tok); len(toks) > apimExprMaxNodes*2 { + return nil, fmt.Errorf("%w: expression is too long", errAPIMExprSyntax) + } + + i = next + } + + return append(toks, apimExprTok{kind: tEOF}), nil +} + +func apimExprIdentRune(r rune, first bool) bool { + return r == '_' || unicode.IsLetter(r) || (!first && unicode.IsDigit(r)) +} + +func apimExprLexTok(rs []rune, i int) (apimExprTok, int, error) { + c := rs[i] + + switch { + case apimExprIdentRune(c, true): + j := i + for j < len(rs) && apimExprIdentRune(rs[j], false) { + j++ + } + + return apimExprTok{kind: tIdent, text: string(rs[i:j])}, j, nil + case c >= '0' && c <= '9': + j := i + for j < len(rs) && rs[j] >= '0' && rs[j] <= '9' { + j++ + } + + n, err := strconv.ParseInt(string(rs[i:j]), 10, 64) + if err != nil || (j < len(rs) && (rs[j] == '.' || unicode.IsLetter(rs[j]))) { + return apimExprTok{}, 0, fmt.Errorf("%w: only integer literals are supported", errAPIMExprSyntax) + } + + return apimExprTok{kind: tInt, val: n, text: string(rs[i:j])}, j, nil + case c == '"': + str, next, err := apimExprLexString(rs, i+1) + + return apimExprTok{kind: tStr, val: str}, next, err + } + + op, ok := apimExprLexOp(rs, i) + if !ok { + return apimExprTok{}, 0, fmt.Errorf("%w: unexpected character %q", errAPIMExprSyntax, string(c)) + } + + return apimExprTok{kind: tOp, text: op}, i + len(op), nil +} + +func apimExprLexOp(rs []rune, i int) (string, bool) { + two := "" + if i+1 < len(rs) { + two = string(rs[i : i+2]) + } + + switch two { + case "==", "!=", "&&", "||", "<=", ">=", "??", "?.": + return two, true + } + + if strings.ContainsRune("()[].,?:!<>+-*/%", rs[i]) { + return string(rs[i]), true + } + + return "", false +} + +func apimExprLexString(rs []rune, i int) (string, int, error) { + var sb strings.Builder + + for ; i < len(rs); i++ { + switch rs[i] { + case '"': + return sb.String(), i + 1, nil + case '\\': + i++ + if i >= len(rs) { + return "", 0, fmt.Errorf("%w: unterminated string", errAPIMExprSyntax) + } + + switch rs[i] { + case 'n': + sb.WriteByte('\n') + case 't': + sb.WriteByte('\t') + case 'r': + sb.WriteByte('\r') + case '\\', '"', '\'': + sb.WriteRune(rs[i]) + default: + return "", 0, fmt.Errorf("%w: unsupported escape \\%c", errAPIMExprSyntax, rs[i]) + } + default: + sb.WriteRune(rs[i]) + } + } + + return "", 0, fmt.Errorf("%w: unterminated string", errAPIMExprSyntax) +} + +type apimExprParser struct { + toks []apimExprTok + pos int + depth int + nodes int +} + +func (p *apimExprParser) peek() apimExprTok { return p.toks[p.pos] } +func (p *apimExprParser) at(i int) apimExprTok { + if p.pos+i < len(p.toks) { + return p.toks[p.pos+i] + } + + return apimExprTok{kind: tEOF} +} + +func (p *apimExprParser) isOp(s string) bool { + t := p.peek() + + return t.kind == tOp && t.text == s +} + +func (p *apimExprParser) eat(s string) bool { + if p.isOp(s) { + p.pos++ + + return true + } + + return false +} + +func (p *apimExprParser) expect(s string) error { + if !p.eat(s) { + return fmt.Errorf("%w: expected %q", errAPIMExprSyntax, s) + } + + return nil +} + +func (p *apimExprParser) node(n *apimExprNode) (*apimExprNode, error) { + if p.nodes++; p.nodes > apimExprMaxNodes { + return nil, fmt.Errorf("%w: expression is too complex", errAPIMExprSyntax) + } + + return n, nil +} + +func (p *apimExprParser) enter() error { + if p.depth++; p.depth > apimExprMaxDepth { + return fmt.Errorf("%w: expression is nested too deeply", errAPIMExprSyntax) + } + + return nil +} + +// apimParseExpr parses the single-expression C# subset documented in PARITY.md. +func apimParseExpr(src string) (*apimExprNode, error) { + if len(src) > apimExprMaxLen { + return nil, fmt.Errorf("%w: expression is longer than %d characters", errAPIMExprSyntax, apimExprMaxLen) + } + + toks, err := apimExprLex(src) + if err != nil { + return nil, err + } + + p := &apimExprParser{toks: toks} + + n, err := p.ternary() + if err != nil { + return nil, err + } + + if p.peek().kind != tEOF { + return nil, fmt.Errorf("%w: unexpected token %q", errAPIMExprSyntax, p.peek().text) + } + + if err = apimExprCheck(n); err != nil { + return nil, err + } + + return n, nil +} + +func (p *apimExprParser) ternary() (*apimExprNode, error) { + if err := p.enter(); err != nil { + return nil, err + } + + defer func() { p.depth-- }() + + c, err := p.binary(0) + if err != nil { + return nil, err + } + + if !p.eat("?") { + return c, nil + } + + a, err := p.ternary() + if err != nil { + return nil, err + } + + if err = p.expect(":"); err != nil { + return nil, err + } + + b, err := p.ternary() + if err != nil { + return nil, err + } + + return p.node(&apimExprNode{kind: nTernary, args: []*apimExprNode{c, a, b}}) +} + +func apimExprPrec() [][]string { + return [][]string{{"??"}, {"||"}, {"&&"}, {"==", "!="}, {"<", ">", "<=", ">="}, {"+", "-"}, {"*", "/", "%"}} +} + +func (p *apimExprParser) binary(level int) (*apimExprNode, error) { + if level >= len(apimExprPrec()) { + return p.unary() + } + + l, err := p.binary(level + 1) + if err != nil { + return nil, err + } + + for { + var op string + + for _, o := range apimExprPrec()[level] { + if p.isOp(o) { + op = o + } + } + + if op == "" { + return l, nil + } + + p.pos++ + + r, rerr := p.binary(level + 1) + if rerr != nil { + return nil, rerr + } + + if l, err = p.node(&apimExprNode{kind: nBinary, op: op, args: []*apimExprNode{l, r}}); err != nil { + return nil, err + } + } +} + +func apimExprIsCastType(s string) bool { + switch s { + case apxString, apxInt, apxTypeBool, apxLong, "IResponse", "Jwt": + return true + } + + return false +} + +func (p *apimExprParser) startsOperand(t apimExprTok) bool { + return t.kind == tIdent || t.kind == tInt || t.kind == tStr || (t.kind == tOp && (t.text == "(" || t.text == "!")) +} + +func (p *apimExprParser) unary() (*apimExprNode, error) { + if err := p.enter(); err != nil { + return nil, err + } + + defer func() { p.depth-- }() + + switch { + case p.isOp("!") || p.isOp("-"): + op := p.peek().text + p.pos++ + + x, err := p.unary() + if err != nil { + return nil, err + } + + return p.node(&apimExprNode{kind: nUnary, op: op, args: []*apimExprNode{x}}) + case p.isOp("(") && p.at(1).kind == tIdent && apimExprIsCastType(p.at(1).text) && + p.at(apimExprGenericClose).kind == tOp && p.at(apimExprGenericClose).text == ")" && + p.startsOperand(p.at(apimExprGenericLen)): + typ := p.at(1).text + p.pos += apimExprGenericLen + + x, err := p.unary() + if err != nil { + return nil, err + } + + return p.node(&apimExprNode{kind: nCast, typ: typ, args: []*apimExprNode{x}}) + } + + return p.postfix() +} + +func (p *apimExprParser) postfix() (*apimExprNode, error) { + x, err := p.primary() + if err != nil { + return nil, err + } + + for { + switch { + case p.isOp(".") || p.isOp("?."): + x, err = p.dotMember(x) + case p.isOp("["): + x, err = p.indexer(x) + default: + return x, nil + } + + if err != nil { + return nil, err + } + } +} + +func (p *apimExprParser) dotMember(x *apimExprNode) (*apimExprNode, error) { + opt := p.peek().text == "?." + p.pos++ + + id := p.peek() + if id.kind != tIdent { + return nil, fmt.Errorf("%w: member name expected", errAPIMExprSyntax) + } + + p.pos++ + + typ := "" + if p.isOp("<") && p.at(1).kind == tIdent && p.at(apimExprGenericClose).kind == tOp && + p.at(apimExprGenericClose).text == ">" { + typ = p.at(1).text + p.pos += apimExprGenericLen + } + + return p.member(x, id.text, typ, opt) +} + +func (p *apimExprParser) indexer(x *apimExprNode) (*apimExprNode, error) { + p.pos++ + + i, err := p.ternary() + if err != nil { + return nil, err + } + + if err = p.expect("]"); err != nil { + return nil, err + } + + return p.node(&apimExprNode{kind: nIndex, args: []*apimExprNode{x, i}}) +} + +func (p *apimExprParser) member(x *apimExprNode, name, typ string, opt bool) (*apimExprNode, error) { + if !p.isOp("(") { + if typ != "" { + return nil, fmt.Errorf("%w: generic arguments need a call", errAPIMExprSyntax) + } + + return p.node(&apimExprNode{kind: nMember, name: name, opt: opt, args: []*apimExprNode{x}}) + } + + p.pos++ + + args := []*apimExprNode{x} + + for !p.isOp(")") { + a, err := p.ternary() + if err != nil { + return nil, err + } + + if args = append(args, a); len(args) > apimExprMaxArgs { + return nil, fmt.Errorf("%w: too many arguments", errAPIMExprSyntax) + } + + if !p.eat(",") { + break + } + } + + if err := p.expect(")"); err != nil { + return nil, err + } + + return p.node(&apimExprNode{kind: nCall, name: name, typ: typ, opt: opt, args: args}) +} + +func (p *apimExprParser) primary() (*apimExprNode, error) { + t := p.peek() + + switch { + case t.kind == tInt || t.kind == tStr: + p.pos++ + + return p.node(&apimExprNode{kind: nLit, val: t.val}) + case t.kind == tIdent: + p.pos++ + + switch t.text { + case apxTrueLit: + return p.node(&apimExprNode{kind: nLit, val: true}) + case apimCFalse: + return p.node(&apimExprNode{kind: nLit, val: false}) + case apxNull: + return p.node(&apimExprNode{kind: nLit}) + } + + return p.node(&apimExprNode{kind: nIdent, name: t.text}) + case p.eat("("): + x, err := p.ternary() + if err != nil { + return nil, err + } + + return x, p.expect(")") + } + + return nil, fmt.Errorf("%w: unexpected token %q", errAPIMExprSyntax, t.text) +} + +func apimExprMemberOK(name string) bool { + return slices.Contains([]string{ + apxRequest, apxResponse, apxVariables, apxSubscription, apxProduct, apxAPI, + apxOperation, apxUser, apxLastError, apxRequestID, apxTimestamp, apxMethod, + apxURL, apxOriginalURL, apxHeaders, apxMatchedParameters, apxIPAddress, apxPath, + apxQuery, apxHost, apxPort, apxScheme, apxQueryString, apxStatusCode, + apxStatusReason, apxID, apxName, apxURLTemplate, apxSource, apxReason, + apxMessage, apxScope, apxSection, apxPolicyID, apxLength, "UtcNow", + "Year", "Month", "Day", "Hour", "Minute", apxSecond, + apxBody, "Claims", "Issuer", "Subject", "Algorithm", "Ordinal", + apxOrdinalIC, "Empty", + }, name) +} + +func apimExprMethodOK(name string) bool { + return slices.Contains([]string{ + apxContains, apxStartsWith, apxEndsWith, "ToLower", "ToUpper", "Equals", + apxTrim, apxToString, "GetValueOrDefault", "ContainsKey", apxParse, "NewGuid", + "AddSeconds", "AddMinutes", "AddHours", "AddDays", "ToLowerInvariant", "As", + "ToUpperInvariant", "IsNullOrEmpty", + }, name) +} + +func apimExprRootOK(name string) bool { + return slices.Contains([]string{apxContext, apxInt, "Guid", apxDateTime, apxString, "StringComparison"}, name) +} + +func apimExprCheck(n *apimExprNode) error { + switch n.kind { + case nIdent: + if !apimExprRootOK(n.name) { + return fmt.Errorf("%w: the identifier '%s' is not supported", errAPIMExprSyntax, n.name) + } + case nMember: + if !apimExprMemberOK(n.name) { + return fmt.Errorf("%w: the member '%s' is not supported", errAPIMExprSyntax, n.name) + } + + if chain, ok := apimExprChain(n); ok { + if err := apimExprCheckChain(chain); err != nil { + return err + } + } + case nCall: + if !apimExprMethodOK(n.name) { + return fmt.Errorf("%w: the method '%s' is not supported", errAPIMExprSyntax, n.name) + } + + if n.typ != "" && !apimExprIsCastType(n.typ) { + return fmt.Errorf("%w: the type '%s' is not supported", errAPIMExprSyntax, n.typ) + } + } + + for _, a := range n.args { + if err := apimExprCheck(a); err != nil { + return err + } + } + + return nil +} + +// apimIsExprText reports whether v is a policy expression; multi is true for the unsupported @{...} form. +func apimIsExprText(v string) (string, bool, bool) { + t := strings.TrimSpace(v) + if strings.HasPrefix(t, "@{") || (strings.HasPrefix(t, "@(") && !strings.HasSuffix(t, ")")) { + return "", false, true + } + + if strings.HasPrefix(t, "@(") && strings.HasSuffix(t, ")") { + return t[2 : len(t)-1], true, false + } + + return "", false, false +} + +// apimExprEnv is the runtime context an expression sees. +type apimExprEnv interface { + member(obj any, name string) (any, error) + now() time.Time +} + +type apimExprDict struct { + get func(string) (any, bool) +} + +type apimExprURL struct { + q map[string][]string + path string + query string + host string + scheme string + port int64 +} + +type apimExprRoot struct{ name string } + +type apimExprStatic struct{ name string } + +type apimExprCounter struct{ n int } + +func apimExprFail(format string, args ...any) error { + return fmt.Errorf("%w: %s", errAPIMExprRuntime, fmt.Sprintf(format, args...)) +} + +func apimEvalExpr(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + if c.n++; c.n > apimExprMaxNodes*4 { + return nil, apimExprFail("evaluation budget exceeded") + } + + switch n.kind { + case nLit: + return n.val, nil + case nIdent: + if n.name == apxContext { + return apimExprRoot{name: apxContext}, nil + } + + return apimExprStatic{name: n.name}, nil + case nMember, nTernary, nCast: + return apimEvalWrapped(n, env, c) + case nCall: + return apimEvalCall(n, env, c) + case nIndex: + return apimEvalIndex(n, env, c) + case nUnary: + return apimEvalUnary(n, env, c) + case nBinary: + return apimEvalBinary(n, env, c) + } + + return nil, apimExprFail("unsupported node") +} + +func apimEvalWrapped(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + x, err := apimEvalExpr(n.args[0], env, c) + if err != nil { + return nil, err + } + + switch n.kind { + case nMember: + if x == nil && n.opt { + return nil, nil //nolint:nilnil // null-conditional access + } + + return apimExprMemberOf(x, n.name, env) + case nCast: + return apimExprCast(n.typ, x) + } + + b, ok := x.(bool) + if !ok { + return nil, apimExprFail("the ternary condition is not a boolean") + } + + if b { + return apimEvalExpr(n.args[1], env, c) + } + + return apimEvalExpr(n.args[2], env, c) +} + +func apimExprCast(typ string, x any) (any, error) { + switch typ { + case apxString: + if s, ok := x.(string); ok || x == nil { + return s, nil + } + case apxInt, apxLong: + if i, ok := x.(int64); ok { + return i, nil + } + case apxTypeBool: + if b, ok := x.(bool); ok { + return b, nil + } + case "IResponse": + if r, ok := x.(*apimExprResponse); ok { + return r, nil + } + case "Jwt": + if j, ok := x.(*apimExprJWT); ok { + return j, nil + } + } + + return nil, apimExprFail("cannot cast the value to %s", typ) +} + +func apimExprMemberOf(x any, name string, env apimExprEnv) (any, error) { + switch v := x.(type) { + case apimExprStatic: + return apimExprStaticMember(v.name, name, env) + case string: + if name == apxLength { + return int64(len([]rune(v))), nil + } + case []string: + if name == apxLength { + return int64(len(v)), nil + } + case time.Time: + return apimExprTimeMember(v, name) + case *apimExprURL: + return apimExprURLMember(v, name) + } + + return env.member(x, name) +} + +func apimExprStaticMember(typ, name string, env apimExprEnv) (any, error) { + switch { + case typ == apxDateTime && name == "UtcNow": + return env.now().UTC(), nil + case typ == "StringComparison" && (name == "Ordinal" || name == apxOrdinalIC): + return apimExprStatic{name: name}, nil + case typ == apxString && name == "Empty": + return "", nil + } + + return nil, apimExprFail("%s.%s is not supported", typ, name) +} + +func apimExprTimeMember(t time.Time, name string) (any, error) { + switch name { + case "Year": + return int64(t.Year()), nil + case "Month": + return int64(t.Month()), nil + case "Day": + return int64(t.Day()), nil + case "Hour": + return int64(t.Hour()), nil + case "Minute": + return int64(t.Minute()), nil + case apxSecond: + return int64(t.Second()), nil + } + + return nil, apimExprFail("DateTime.%s is not supported", name) +} + +func apimExprURLMember(u *apimExprURL, name string) (any, error) { + switch name { + case apxPath: + return u.path, nil + case apxHost: + return u.host, nil + case apxScheme: + return u.scheme, nil + case apxPort: + return u.port, nil + case apxQueryString: + return u.query, nil + case apxQuery: + return &apimExprDict{ + get: func(k string) (any, bool) { + v, ok := u.q[k] + + return v, ok + }, + }, nil + } + + return nil, apimExprFail("Url.%s is not supported", name) +} + +func apimEvalIndex(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + x, err := apimEvalExpr(n.args[0], env, c) + if err != nil { + return nil, err + } + + i, err := apimEvalExpr(n.args[1], env, c) + if err != nil { + return nil, err + } + + switch v := x.(type) { + case *apimExprDict: + k, ok := i.(string) + if !ok { + return nil, apimExprFail("a dictionary key must be a string") + } + + val, found := v.get(k) + if !found { + return nil, apimExprFail("the key '%s' was not found", k) + } + + return val, nil + case []string: + idx, ok := i.(int64) + if !ok || idx < 0 || int(idx) >= len(v) { + return nil, apimExprFail("index out of range") + } + + return v[idx], nil + } + + return nil, apimExprFail("the value cannot be indexed") +} + +func apimEvalUnary(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + x, err := apimEvalExpr(n.args[0], env, c) + if err != nil { + return nil, err + } + + switch v := x.(type) { + case bool: + if n.op == "!" { + return !v, nil + } + case int64: + if n.op == "-" { + return -v, nil + } + } + + return nil, apimExprFail("operator %s cannot be applied to the operand", n.op) +} + +func apimExprString(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return t + case int64: + return strconv.FormatInt(t, 10) + case bool: + if t { + return apimExprTrue + } + + return apimExprFalse + case time.Time: + return t.UTC().Format("01/02/2006 3:04:05 PM") + case []string: + return strings.Join(t, ",") + } + + return fmt.Sprint(v) +} + +func apimEvalBinary(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + l, err := apimEvalExpr(n.args[0], env, c) + if err != nil { + return nil, err + } + + switch n.op { + case "&&", "||": + lb, ok := l.(bool) + if !ok { + return nil, apimExprFail("operator %s needs boolean operands", n.op) + } + + if (n.op == "&&" && !lb) || (n.op == "||" && lb) { + return lb, nil + } + + r, rerr := apimEvalExpr(n.args[1], env, c) + if rerr != nil { + return nil, rerr + } + + rb, ok := r.(bool) + if !ok { + return nil, apimExprFail("operator %s needs boolean operands", n.op) + } + + return rb, nil + case "??": + if l != nil { + return l, nil + } + + return apimEvalExpr(n.args[1], env, c) + } + + r, err := apimEvalExpr(n.args[1], env, c) + if err != nil { + return nil, err + } + + return apimExprBinOp(n.op, l, r) +} + +func apimExprBinOp(op string, l, r any) (any, error) { + switch op { + case "==": + return apimExprEqual(l, r) + case "!=": + eq, err := apimExprEqual(l, r) + if err != nil { + return nil, err + } + + same, _ := eq.(bool) + + return !same, nil + case "+": + if _, ls := l.(string); ls { + return apimExprConcat(l, r) + } + + if _, rs := r.(string); rs { + return apimExprConcat(l, r) + } + } + + if res, ok, err := apimExprOrdered(op, l, r); ok { + return res, err + } + + li, lok := l.(int64) + ri, rok := r.(int64) + + if !lok || !rok { + return nil, apimExprFail("operator %s cannot be applied to the operands", op) + } + + return apimExprIntOp(op, li, ri) +} + +func apimExprConcat(l, r any) (any, error) { + s := apimExprString(l) + apimExprString(r) + if len(s) > apimExprMaxString { + return nil, apimExprFail("string result is too large") + } + + return s, nil +} + +// apimExprOrdered compares two times, or two strings with a relational operator. +func apimExprOrdered(op string, l, r any) (any, bool, error) { + if lt, ok := l.(time.Time); ok { + if rt, ok2 := r.(time.Time); ok2 { + res, err := apimExprCompare(op, lt.Compare(rt)) + + return res, true, err + } + } + + ls, ok := l.(string) + rs, ok2 := r.(string) + + if ok && ok2 && (op == "<" || op == ">" || op == "<=" || op == ">=") { + res, err := apimExprCompare(op, strings.Compare(ls, rs)) + + return res, true, err + } + + return nil, false, nil +} + +func apimExprIntOp(op string, li, ri int64) (any, error) { + switch op { + case "+": + return li + ri, nil + case "-": + return li - ri, nil + case "*": + return li * ri, nil + case "/", "%": + if ri == 0 { + return nil, apimExprFail("division by zero") + } + + if op == "/" { + return li / ri, nil + } + + return li % ri, nil + } + + return apimExprCompare(op, cmp.Compare(li, ri)) +} + +func apimExprCompare(op string, cmp int) (any, error) { + switch op { + case "<": + return cmp < 0, nil + case ">": + return cmp > 0, nil + case "<=": + return cmp <= 0, nil + case ">=": + return cmp >= 0, nil + } + + return nil, apimExprFail("operator %s is not supported", op) +} + +func apimExprEqual(l, r any) (any, error) { + if l == nil || r == nil { + return l == nil && r == nil, nil + } + + switch lv := l.(type) { + case string: + if rv, ok := r.(string); ok { + return lv == rv, nil + } + case int64: + if rv, ok := r.(int64); ok { + return lv == rv, nil + } + case bool: + if rv, ok := r.(bool); ok { + return lv == rv, nil + } + case time.Time: + if rv, ok := r.(time.Time); ok { + return lv.Equal(rv), nil + } + } + + return nil, apimExprFail("the operands of == have different types") +} + +func apimEvalCall(n *apimExprNode, env apimExprEnv, c *apimExprCounter) (any, error) { + recv, err := apimEvalExpr(n.args[0], env, c) + if err != nil { + return nil, err + } + + if recv == nil && n.opt { + return nil, nil //nolint:nilnil // null-conditional call + } + + args := make([]any, 0, len(n.args)-1) + + for _, a := range n.args[1:] { + v, aerr := apimEvalExpr(a, env, c) + if aerr != nil { + return nil, aerr + } + + args = append(args, v) + } + + if n.name == apxToString && len(args) == 0 { + return apimExprString(recv), nil + } + + return apimExprDispatch(recv, n, args, env) +} + +func apimExprDispatch(recv any, n *apimExprNode, args []any, env apimExprEnv) (any, error) { + switch r := recv.(type) { + case apimExprStatic: + return apimExprStaticCall(r.name, n.name, args) + case string: + return apimExprStringCall(r, n.name, args) + case *apimExprDict: + return apimExprDictCall(r, n, args) + case time.Time: + return apimExprTimeCall(r, n.name, args) + case apimExprBody: + if n.name == "As" && n.typ == apxString { + return string(r.b), nil + } + case []string: + if n.name == apxContains && len(args) == 1 { + s, _ := args[0].(string) + + return slices.Contains(r, s), nil + } + } + + _ = env + + return nil, apimExprFail("the method %s is not supported on this value", n.name) +} + +func apimExprStaticCall(typ, name string, args []any) (any, error) { + switch { + case typ == apxInt && name == apxParse && len(args) == 1: + return apimExprIntParse(args[0]) + case typ == "Guid" && name == "NewGuid" && len(args) == 0: + return uuid.NewString(), nil + case typ == apxString && name == "IsNullOrEmpty" && len(args) == 1: + s, _ := args[0].(string) + + return s == "", nil + case typ == apxDateTime && name == apxParse && len(args) == 1: + s, _ := args[0].(string) + + t, err := time.Parse(time.RFC3339, s) + if err != nil { + return nil, apimExprFail("the string is not a valid DateTime") + } + + return t.UTC(), nil + } + + return nil, apimExprFail("%s.%s is not supported", typ, name) +} + +func apimExprIntParse(arg any) (any, error) { + s, ok := arg.(string) + if !ok { + return nil, apimExprFail("int.Parse needs a string") + } + + i, err := strconv.ParseInt(strings.TrimSpace(s), 10, 32) + if err != nil { + return nil, apimExprFail("input string '%s' was not in a correct format", s) + } + + return i, nil +} + +func apimExprFold(args []any, i int) (bool, error) { + if len(args) <= i { + return false, nil + } + + st, ok := args[i].(apimExprStatic) + if !ok { + return false, apimExprFail("the comparison argument must be a StringComparison value") + } + + return st.name == apxOrdinalIC, nil +} + +func apimExprStringCall(s, name string, args []any) (any, error) { + arg := "" + if len(args) > 0 { + a, ok := args[0].(string) + if !ok && name != apxToString { + return nil, apimExprFail("%s needs a string argument", name) + } + + arg = a + } + + switch name { + case "ToLower", "ToLowerInvariant": + return strings.ToLower(s), nil + case "ToUpper", "ToUpperInvariant": + return strings.ToUpper(s), nil + case apxTrim: + return strings.TrimSpace(s), nil + case apxContains, apxStartsWith, apxEndsWith, "Equals": + fold, err := apimExprFold(args, 1) + if err != nil { + return nil, err + } + + if len(args) == 0 { + return nil, apimExprFail("%s needs an argument", name) + } + + if fold { + s, arg = strings.ToLower(s), strings.ToLower(arg) + } + + switch name { + case apxContains: + return strings.Contains(s, arg), nil + case apxStartsWith: + return strings.HasPrefix(s, arg), nil + case apxEndsWith: + return strings.HasSuffix(s, arg), nil + } + + return s == arg, nil + } + + return nil, apimExprFail("string.%s is not supported", name) +} + +func apimExprDictCall(d *apimExprDict, n *apimExprNode, args []any) (any, error) { + if len(args) == 0 { + return nil, apimExprFail("%s needs arguments", n.name) + } + + key, isStr := args[0].(string) + if !isStr { + return nil, apimExprFail("a dictionary key must be a string") + } + + v, found := d.get(key) + + switch n.name { + case "ContainsKey": + return found, nil + case "GetValueOrDefault": + if len(args) == 1 && n.typ != "" { + args = append(args, apimExprZero(n.typ)) + } + + if len(args) != apimExprKeyDefault { + return nil, apimExprFail("GetValueOrDefault needs a key and a default") + } + + if !found { + return args[1], nil + } + + if sl, ok := v.([]string); ok { + return strings.Join(sl, ","), nil + } + + return v, nil + } + + return nil, apimExprFail("%s is not supported on a dictionary", n.name) +} + +func apimExprTimeCall(t time.Time, name string, args []any) (any, error) { + if len(args) == 1 && name == apxToString { + f, _ := args[0].(string) + + switch f { + case "o", "O": + return t.UTC().Format("2006-01-02T15:04:05.0000000Z"), nil + case "s": + return t.UTC().Format("2006-01-02T15:04:05"), nil + case "yyyy-MM-ddTHH:mm:ssZ": + return t.UTC().Format("2006-01-02T15:04:05Z"), nil + } + + return nil, apimExprFail("the DateTime format '%s' is not supported", f) + } + + if len(args) == 1 { + if i, ok := args[0].(int64); ok { + switch name { + case "AddSeconds": + return t.Add(time.Duration(i) * time.Second), nil + case "AddMinutes": + return t.Add(time.Duration(i) * time.Minute), nil + case "AddHours": + return t.Add(time.Duration(i) * time.Hour), nil + case "AddDays": + return t.AddDate(0, 0, int(i)), nil + } + } + } + + return nil, apimExprFail("DateTime.%s is not supported", name) +} + +// apimExprChain returns the member names of a pure context.A.B.C chain. +func apimExprChain(n *apimExprNode) ([]string, bool) { + var rev []string + + for n.kind == nMember { + rev = append(rev, n.name) + n = n.args[0] + } + + if n.kind != nIdent || n.name != apxContext { + return nil, false + } + + slices.Reverse(rev) + + return rev, true +} + +func apimExprContext() map[string][]string { + return map[string][]string{ + apxRequest: {apxMethod, apxURL, apxOriginalURL, apxHeaders, apxMatchedParameters, apxIPAddress}, + apxResponse: {apxStatusCode, apxStatusReason, apxHeaders}, + apxVariables: {}, + apxSubscription: {apxID, apxName}, + apxProduct: {apxID, apxName}, + apxAPI: {apxID, apxName, apxPath}, + apxOperation: {apxID, apxName, apxMethod, apxURLTemplate}, + apxUser: {apxID}, + apxLastError: {apxSource, apxReason, apxMessage, apxScope, apxSection, apxPath, apxPolicyID}, + apxRequestID: {}, + apxTimestamp: {}, + } +} + +func apimExprURLParts() []string { + return []string{apxPath, apxQuery, apxHost, apxPort, apxScheme, apxQueryString} +} + +func apimExprCheckChain(chain []string) error { + allowed, ok := apimExprContext()[chain[0]] + if !ok { + return fmt.Errorf("%w: context.%s is not supported", errAPIMExprSyntax, chain[0]) + } + + if len(chain) == 1 { + return nil + } + + if len(chain) == 2 && slices.Contains(allowed, chain[1]) { + return nil + } + + if len(chain) == 3 && chain[0] == apxRequest && (chain[1] == apxURL || chain[1] == apxOriginalURL) && + slices.Contains(apimExprURLParts(), chain[2]) { + return nil + } + + return fmt.Errorf("%w: context.%s is not supported", errAPIMExprSyntax, strings.Join(chain, ".")) +} + +var apimXMLEntityRE = regexp.MustCompile(`^&(amp|lt|gt|quot|apos|#[0-9]+|#x[0-9a-fA-F]+);`) + +// apimEscapeExpressions XML-escapes the body of each @(...) and @{...} expression, as the real gateway accepts +// documented policies that write unescaped quotes, ampersands and angle brackets inside expressions. +func apimEscapeExpressions(doc string) string { + if !strings.Contains(doc, "@(") && !strings.Contains(doc, "@{") { + return doc + } + + var sb strings.Builder + + for i := 0; i < len(doc); { + if doc[i] != '@' || i+1 >= len(doc) || (doc[i+1] != '(' && doc[i+1] != '{') { + sb.WriteByte(doc[i]) + i++ + + continue + } + + end := apimExprEnd(doc, i+1) + if end < 0 { + sb.WriteString(doc[i:]) + + break + } + + sb.WriteString(doc[i : i+2]) + sb.WriteString(apimEscapeExprBody(doc[i+2 : end])) + sb.WriteByte(doc[end]) + + i = end + 1 + } + + return sb.String() +} + +// apimExprEnd returns the index of the bracket closing the one at open, skipping C# string literals. +func apimExprEnd(doc string, open int) int { + depth, inStr := 0, false + + for i := open; i < len(doc); i++ { + c := doc[i] + + switch { + case inStr && c == '\\': + i++ + case c == '"' || (inStr && strings.HasPrefix(doc[i:], """)): + if c != '"' { + i += len(""") - 1 + } + + inStr = !inStr + case inStr: + case c == '(' || c == '{': + depth++ + case c == ')' || c == '}': + if depth--; depth == 0 { + return i + } + } + } + + return -1 +} + +func apimEscapeExprBody(body string) string { + var sb strings.Builder + + for i := range len(body) { + switch body[i] { + case '&': + if apimXMLEntityRE.MatchString(body[i:]) { + sb.WriteByte('&') + } else { + sb.WriteString("&") + } + case '<': + sb.WriteString("<") + case '"': + sb.WriteString(""") + default: + sb.WriteByte(body[i]) + } + } + + return sb.String() +} + +func apimExprZero(typ string) any { + switch typ { + case apxTypeBool: + return false + case apxInt, apxLong: + return int64(0) + } + + return nil +} diff --git a/services/azurearm/rp_apim_filter.go b/services/azurearm/rp_apim_filter.go index 39b46a83c8..d952627d61 100644 --- a/services/azurearm/rp_apim_filter.go +++ b/services/azurearm/rp_apim_filter.go @@ -59,7 +59,7 @@ var ( "policyfragments": fieldsOf("name", "description", "value"), } apimOperationFields = map[string]apimFilterField{ - fieldName: {}, apimFieldDisplay: {}, "method": {}, apimFieldDesc: {}, "urltemplate": {}, + fieldName: {}, apimFieldDisplay: {}, apimCMethod: {}, apimFieldDesc: {}, "urltemplate": {}, } ) diff --git a/services/azurearm/rp_apim_gateway.go b/services/azurearm/rp_apim_gateway.go index 78042df730..e279052d66 100644 --- a/services/azurearm/rp_apim_gateway.go +++ b/services/azurearm/rp_apim_gateway.go @@ -1,11 +1,14 @@ package azurearm import ( + "crypto/tls" "encoding/json/jsontext" "encoding/json/v2" "errors" "net" "net/http" + "path" + "sort" "strings" "syscall" "time" @@ -39,50 +42,114 @@ var ErrAPIMDestinationNotPermitted = errors.New( "azurearm: apim backend is outside loopback and external backends are not allowed", ) +type apimHit struct { + at time.Time + n int +} + type apimLimiter struct { mu *lockmetrics.RWMutex - win map[string][]time.Time + win map[string][]apimHit } func newAPIMLimiter() *apimLimiter { - return &apimLimiter{mu: lockmetrics.New("azurearm.apim.limiter"), win: map[string][]time.Time{}} + return &apimLimiter{mu: lockmetrics.New("azurearm.apim.limiter"), win: map[string][]apimHit{}} } func (l *apimLimiter) reset() { l.mu.Lock("reset") - l.win = map[string][]time.Time{} + l.win = map[string][]apimHit{} l.mu.Unlock() } -// take counts one call in a sliding window of period; it reports whether the call is allowed, the calls left and, -// when denied, the time until the oldest counted call leaves the window. -func (l *apimLimiter) take(key string, calls int, period time.Duration, now time.Time) (bool, int, time.Duration) { - l.mu.Lock("take") - defer l.mu.Unlock() +func (l *apimLimiter) sweep(period time.Duration, now time.Time) { + if len(l.win) <= apimLimiterSweepAt { + return + } - if len(l.win) > apimLimiterSweepAt { - for k, w := range l.win { - if len(w) == 0 || !now.Before(w[len(w)-1].Add(period)) { - delete(l.win, k) - } + for k, w := range l.win { + if len(w) == 0 || !now.Before(w[len(w)-1].at.Add(period)) { + delete(l.win, k) } } +} - w := l.win[key] - for len(w) > 0 && !now.Before(w[0].Add(period)) { +func apimWindowCount(w []apimHit) int { + t := 0 + for _, h := range w { + t += h.n + } + + return t +} + +// trim drops the hits that left the window and returns the live ones. +func apimTrimWindow(w []apimHit, period time.Duration, now time.Time) []apimHit { + for len(w) > 0 && !now.Before(w[0].at.Add(period)) { w = w[1:] } - if len(w) >= calls { + return w +} + +// apimRetryAfter is the time until enough weight leaves the window for n more calls to fit. +func apimRetryAfter(w []apimHit, calls, n int, period time.Duration, now time.Time) time.Duration { + over := apimWindowCount(w) + n - calls + + for _, h := range w { + over -= h.n + if over <= 0 { + return h.at.Add(period).Sub(now) + } + } + + return period +} + +// take counts n calls in a sliding window of period; it reports whether they are allowed, the calls left and, +// when denied, the time until enough of the window has passed. +func (l *apimLimiter) take(key string, calls, n int, period time.Duration, now time.Time) (bool, int, time.Duration) { + l.mu.Lock("take") + defer l.mu.Unlock() + + l.sweep(period, now) + + w := apimTrimWindow(l.win[key], period, now) + if apimWindowCount(w)+n > calls { l.win[key] = w - return false, 0, w[len(w)-calls].Add(period).Sub(now) + return false, max(0, calls-apimWindowCount(w)), apimRetryAfter(w, calls, n, period, now) } - w = append(w, now) + w = append(w, apimHit{at: now, n: n}) + l.win[key] = w + + return true, calls - apimWindowCount(w), 0 +} + +// peek reports whether one more call would be allowed without counting it. +func (l *apimLimiter) peek(key string, calls int, period time.Duration, now time.Time) (bool, int, time.Duration) { + l.mu.Lock("peek") + defer l.mu.Unlock() + + w := apimTrimWindow(l.win[key], period, now) l.win[key] = w - return true, calls - len(w), 0 + if apimWindowCount(w) >= calls { + return false, 0, apimRetryAfter(w, calls, 1, period, now) + } + + return true, calls - apimWindowCount(w), 0 +} + +// add counts n calls unconditionally. +func (l *apimLimiter) add(key string, n int, period time.Duration, now time.Time) { + l.mu.Lock("add") + defer l.mu.Unlock() + + l.sweep(period, now) + + l.win[key] = append(apimTrimWindow(l.win[key], period, now), apimHit{at: now, n: n}) } func (p *APIMProvider) newBackendClient() *http.Client { @@ -109,6 +176,10 @@ func (p *APIMProvider) newBackendClient() *http.Client { }, }).DialContext + if p.rootCAs != nil { + tr.TLSClientConfig = &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: p.rootCAs} + } + return &http.Client{ Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, @@ -130,18 +201,30 @@ type gwBackend struct { // gwPlan is the immutable view of the service the gateway needs for one request. type gwPlan struct { - now func() time.Time - api map[string]any - op map[string]any - named map[string]string - backends map[string]gwBackend - params map[string]string - service string - subID string - suffix string - apiID string - docs [3]string - preflght bool + now func() time.Time + api map[string]any + op map[string]any + named map[string]string + backends map[string]gwBackend + params map[string]string + fragments map[string]string + certs map[string]gwCert + subStart time.Time + service string + svcKey string + subID string + ownerID string + userID string + productID string + productName string + path string + opID string + suffix string + apiID string + subScope string + docs [4]string + groups []string + preflght bool } func gatewayTarget(r *http.Request) (string, string, bool) { @@ -214,20 +297,33 @@ func (p *APIMProvider) resolveGateway(name, path string, r *http.Request) (*gwPl } api, suffix := s.matchAPI(path) - if api == nil || !apiAllowsScheme(api.Props, r.TLS != nil) { + want := acaScaleHTTP + if r.TLS != nil { + want = acaSchemeHTTPS + } + + if apimIsWebSocket(r) { + want = apimWSScheme(r.TLS != nil) + } + + if api == nil || !apiAllowsScheme(api.Props, want) { return nil, &gwFail{status: http.StatusNotFound, msg: apimMsgNoOperation} } plan := &gwPlan{ - now: p.now, - service: s.Name, - api: api.Props, - apiID: api.ID, - suffix: suffix, - named: s.namedMap(), - backends: s.backendMap(), - } - plan.docs[0], plan.docs[1] = s.policyDoc(""), s.policyDoc("apis/"+api.ID) + now: p.now, + service: s.Name, + svcKey: apimKey(s.SubID, s.ResourceGrp, s.Name), + path: path, + api: api.Props, + apiID: api.ID, + suffix: suffix, + named: s.namedMap(), + fragments: s.fragmentMap(), + certs: s.certMap(), + backends: s.backendMap(), + } + plan.docs[0], plan.docs[2] = s.policyDoc(""), s.policyDoc("apis/"+api.ID) if r.Method == http.MethodOptions && r.Header.Get(apimCOriginX) != "" && r.Header.Get(apimCAccessControlRequestMethod) != "" { @@ -242,13 +338,15 @@ func (p *APIMProvider) resolveGateway(name, path string, r *http.Request) (*gwPl return nil, &gwFail{status: http.StatusNotFound, msg: apimMsgNoOperation} } - plan.op, plan.params = op, params - plan.docs[2] = s.policyDoc("apis/" + api.ID + "/operations/" + opID) + plan.op, plan.params, plan.opID = op, params, opID + plan.docs[3] = s.policyDoc("apis/" + api.ID + "/operations/" + opID) if fail := p.checkKey(s, api, plan, r); fail != nil { return nil, fail } + s.fillContext(plan) + return plan, nil } @@ -294,12 +392,7 @@ func (s *apimService) backendMap() map[string]gwBackend { return out } -func apiAllowsScheme(props map[string]any, tls bool) bool { - want := acaScaleHTTP - if tls { - want = acaSchemeHTTPS - } - +func apiAllowsScheme(props map[string]any, want string) bool { for _, v := range strList(props[apimCProtocols]) { if strings.EqualFold(v, want) { return true @@ -318,6 +411,10 @@ func (s *apimService) matchAPI(path string) (*apimEntity, string) { ) for _, e := range s.APIs { + if cur, has := e.Props[apimCurrent].(bool); has && !cur { + continue + } + ap := strings.ToLower(strOf(e.Props, apimCPath)) if len(norm) < len(ap) || !strings.EqualFold(norm[:len(ap)], ap) { continue @@ -420,6 +517,9 @@ func (p *APIMProvider) checkKey(s *apimService, api *apimEntity, plan *gwPlan, r if key != "" { if sub := s.activeSubscription(key, api.ID); sub != nil { plan.subID = sub.ID + plan.subScope = strOf(sub.Props, acrPropScope) + plan.ownerID = path.Base(strOf(sub.Props, "ownerId")) + plan.subStart, _ = time.Parse(time.RFC3339, strOf(sub.Props, apimCStartDate)) return nil } @@ -494,3 +594,49 @@ func hostOnly(addr string) string { return h } + +// fillContext resolves the product, groups and user the policy expressions and the product-scope policy see. +func (s *apimService) fillContext(plan *gwPlan) { + if plan.ownerID == "." || plan.ownerID == "/" { + plan.ownerID = "" + } + + plan.userID = plan.ownerID + + ids := make([]string, 0, len(s.Products)) + for _, e := range s.Products { + ids = append(ids, e.ID) + } + + sort.Strings(ids) + + base := strings.ToLower(s.armBase()) + "/products/" + scoped, isProduct := strings.CutPrefix(strings.ToLower(plan.subScope), base) + + for _, id := range ids { + prod := s.Products[entKey("", id)] + subReq, _ := prod.Props[apimCSubscriptionRequired].(bool) + picked := (isProduct && strings.EqualFold(scoped, id)) || (plan.subID == "" && !subReq) + + if !s.ProductAPIs[entKey(id, plan.apiID)] || !picked { + continue + } + + plan.productID, plan.productName = id, strOf(prod.Props, apimCDisplayName) + plan.docs[1] = s.policyDoc("products/" + id) + + break + } + + if plan.ownerID == "" { + return + } + + for _, g := range s.Generic[apimGroupsType] { + if s.Links[apimLinkKey(apimLinkGroupUser, g.ID, plan.ownerID)] { + plan.groups = append(plan.groups, g.ID) + } + } + + sort.Strings(plan.groups) +} diff --git a/services/azurearm/rp_apim_gwctl.go b/services/azurearm/rp_apim_gwctl.go new file mode 100644 index 0000000000..041f41c53d --- /dev/null +++ b/services/azurearm/rp_apim_gwctl.go @@ -0,0 +1,551 @@ +package azurearm + +import ( + "encoding/json/v2" + "errors" + "net/http" + "net/textproto" + "strconv" + "strings" + "time" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const ( + apimKindRequest = "request" + apimKindResponse = "response" + apimKindSubscription = "subscription" + apimCChoose = "choose" + apimCWhen = "when" + apimCOtherwise = "otherwise" + apimCSetVariable = "set-variable" + apimCCondition = "condition" + apimCID = "id" + apimMaxVars = 256 + apimMaxVarBytes = 1 << 20 + apimReasonExpr = "ExpressionValueEvaluationFailure" + apimSourceConfig = "configuration" + apimScopeGlobal = "global" + apimScopeProduct = "product" + apimScopeAPI = "api" + apimScopeOp = "operation" + apimPathSeparator = `\` +) + +// gwLastError is context.LastError of the error-handling reference. +type gwLastError struct { + Source, Reason, Message, Scope, Section, Path, PolicyID string +} + +type apimExprObj struct{ kind string } + +func (g *gwState) now() time.Time { return g.plan.now() } + +// subVal expands named values and evaluates a policy expression; evaluation failures are recorded in evalErr. +func (g *gwState) subVal(s string) any { + if body, ok, _ := apimIsExprText(s); ok { + n, err := apimParseExpr(body) + if err == nil { + var v any + + if v, err = apimEvalExpr(n, g, &apimExprCounter{}); err == nil { + return v + } + } + + if g.evalErr == nil { + g.evalErr = err + } + + return nil + } + + return apimNamedRefRE.ReplaceAllStringFunc(s, func(m string) string { + return g.plan.named[strings.ToLower(m[2:len(m)-2])] + }) +} + +func (g *gwState) boolAttr(n *polNode, attr string, def bool) bool { + raw, ok := n.Attrs[attr] + if !ok { + return def + } + + switch v := g.subVal(raw).(type) { + case bool: + return v + case string: + return strings.EqualFold(strings.TrimSpace(v), cmpTrue) + } + + return def +} + +func (g *gwState) intAttr(n *polNode, attr string, def int64) int64 { + raw, ok := n.Attrs[attr] + if !ok { + return def + } + + switch v := g.subVal(raw).(type) { + case int64: + return v + case string: + if i, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64); err == nil { + return i + } + } + + if g.evalErr == nil { + g.evalErr = apimExprFail("the attribute '%s' is not an integer", attr) + } + + return def +} + +func (g *gwState) member(obj any, name string) (any, error) { + switch o := obj.(type) { + case apimExprRoot: + return g.rootMember(name) + case apimExprObj: + return g.objMember(o.kind, name) + case *apimExprResponse: + return o.member(name) + case *apimExprJWT: + return o.member(name) + case apimExprBody: + return nil, apimExprFail("Body.%s is not supported", name) + } + + return nil, apimExprFail("the member %s was accessed on a null or unsupported value", name) +} + +func (g *gwState) rootMember(name string) (any, error) { + switch name { + case apxRequest: + return apimExprObj{apimKindRequest}, nil + case apxResponse: + if g.status == 0 { + return nil, nil //nolint:nilnil // context.Response is null before a response exists + } + + return apimExprObj{apimKindResponse}, nil + case apxVariables: + return &apimExprDict{get: func(k string) (any, bool) { + v, ok := g.vars[k] + + return v, ok + }}, nil + case apxSubscription: + return g.nullable(g.plan.subID != "", apimKindSubscription), nil + case apxProduct: + return g.nullable(g.plan.productID != "", apimScopeProduct), nil + case apxUser: + return g.nullable(g.plan.userID != "", "user"), nil + case apxLastError: + return g.nullable(g.lastErr != nil, "lasterror"), nil + case apxAPI: + return apimExprObj{"api"}, nil + case apxOperation: + return g.nullable(g.plan.op != nil, "operation"), nil + case apxTimestamp: + return g.start().UTC(), nil + case apxRequestID: + return g.requestID(), nil + } + + return nil, apimExprFail("context.%s is not supported", name) +} + +func (g *gwState) nullable(ok bool, kind string) any { + if !ok { + return nil + } + + return apimExprObj{kind} +} + +func (g *gwState) objMember(kind, name string) (any, error) { + var ( + v any + ok bool + ) + + switch kind { + case apimKindRequest: + return g.requestMember(name) + case apimKindResponse: + v, ok = g.responseMember(name) + case apimKindSubscription: + v, ok = g.plan.subID, name == apxID || name == apxName + case apimScopeProduct: + v, ok = g.productMember(name) + case "user": + v, ok = g.plan.userID, name == apxID + case "api": + v, ok = g.apiMember(name) + case "operation": + v, ok = g.operationMember(name) + case "lasterror": + return g.lastErrorMember(name) + } + + if !ok { + return nil, apimExprFail("%s.%s is not supported", kind, name) + } + + return v, nil +} + +func (g *gwState) responseMember(name string) (any, bool) { + switch name { + case apxStatusCode: + return int64(g.status), true + case apxStatusReason: + return http.StatusText(g.status), true + case apxHeaders: + return apimHeaderDict(g.respHeader), true + } + + return nil, false +} + +func (g *gwState) productMember(name string) (any, bool) { + switch name { + case apxID: + return g.plan.productID, true + case apxName: + return g.plan.productName, true + } + + return nil, false +} + +func (g *gwState) apiMember(name string) (any, bool) { + switch name { + case apxID: + return g.plan.apiID, true + case apxName: + return strOf(g.plan.api, apimCDisplayName), true + case apxPath: + return strOf(g.plan.api, apimCPath), true + } + + return nil, false +} + +func (g *gwState) operationMember(name string) (any, bool) { + switch name { + case apxID: + return g.plan.opID, true + case apxName: + return strOf(g.plan.op, apimCDisplayName), true + case apxMethod: + return strings.ToUpper(strOf(g.plan.op, apimCMethod)), true + case apxURLTemplate: + return strOf(g.plan.op, apimCUrlTemplate), true + } + + return nil, false +} + +func (g *gwState) lastErrorMember(name string) (any, error) { + e := g.lastErr + + switch name { + case apxSource: + return e.Source, nil + case apxReason: + return e.Reason, nil + case apxMessage: + return e.Message, nil + case apxScope: + return e.Scope, nil + case apxSection: + return e.Section, nil + case apxPath: + return e.Path, nil + case apxPolicyID: + return e.PolicyID, nil + } + + return nil, apimExprFail("LastError.%s is not supported", name) +} + +func (g *gwState) requestMember(name string) (any, error) { + switch name { + case apxMethod: + return g.r.Method, nil + case apxIPAddress: + return hostOnly(g.r.RemoteAddr), nil + case apxHeaders: + return apimHeaderDict(g.header), nil + case apxMatchedParameters: + return &apimExprDict{get: func(k string) (any, bool) { + for pk, v := range g.plan.params { + if strings.EqualFold(pk, k) { + return v, true + } + } + + return nil, false + }}, nil + case apxURL, apxOriginalURL: + host, port := g.r.Host, int64(0) + if h, p, ok := strings.Cut(host, ":"); ok { + host = h + port, _ = strconv.ParseInt(p, 10, 64) + } + + scheme := acaScaleHTTP + if g.r.TLS != nil { + scheme = acaSchemeHTTPS + } + + u := &apimExprURL{path: g.plan.path, host: host, scheme: scheme, port: port} + if name == apxURL { + u.q, u.query = g.query, "?"+g.query.Encode() + } else { + u.q, u.query = g.r.URL.Query(), "?"+g.r.URL.RawQuery + } + + return u, nil + } + + return nil, apimExprFail("Request.%s is not supported", name) +} + +func apimHeaderDict(h http.Header) *apimExprDict { + return &apimExprDict{get: func(k string) (any, bool) { + v := h.Values(textproto.CanonicalMIMEHeaderKey(k)) + + return v, len(v) > 0 + }} +} + +func (g *gwState) start() time.Time { + if g.t0.IsZero() { + g.t0 = g.now() + } + + return g.t0 +} + +func (g *gwState) requestID() string { + if g.reqID == "" { + g.reqID = apimNewGUID() + } + + return g.reqID +} + +// failR records an error response and its LastError and ends the current section. +func (g *gwState) failR(status int, reason, msg string) { + if g.errored { + return + } + + body, _ := json.Marshal(map[string]any{apimCStatusCode: status, fieldMessage: msg}, jsonx.V1()) + g.setResponse(status, http.Header{apimCContentType: {"application/json"}}, body) + g.short, g.errored = true, true + + e := &gwLastError{Reason: reason, Message: msg, Section: g.section, Path: g.path} + if n := g.cur; n != nil { + e.Source, e.PolicyID = n.Name, n.Attrs[apimCID] + e.Scope = apimScopeName(n.Scope) + } else { + e.Source = apimSourceConfig + } + + g.lastErr = e +} + +func apimScopeName(scope string) string { + _, idx, _ := strings.Cut(scope, "|") + + switch idx { + case "0": + return apimScopeGlobal + case "1": + return apimScopeProduct + case "2": + return apimScopeAPI + case "3": + return apimScopeOp + } + + return "" +} + +func (g *gwState) raiseEval() { + err := g.evalErr + g.evalErr = nil + + msg := "Expression evaluation failed." + if err != nil { + msg += " " + strings.TrimPrefix(err.Error(), errAPIMExprRuntime.Error()+": ") + } + + if errors.Is(err, errAPIMExprSyntax) { + msg = "Expression could not be compiled. " + err.Error() + } + + g.failR(http.StatusInternalServerError, apimReasonExpr, msg) +} + +// execList runs statements in order; it stops at a short-circuit, an error or a cache hit (inbound). +func (g *gwState) execList(nodes []*polNode, section, path string) { + for _, n := range nodes { + g.cur, g.section = n, section + + g.execNode(n, section, path) + + if g.evalErr != nil { + g.cur, g.section = n, section + g.raiseEval() + } + + if g.short || g.errored || (g.cacheHit && section == polInbound) { + return + } + } +} + +func (g *gwState) execNode(n *polNode, section, path string) { + switch n.Name { + case apimCChoose: + g.choose(n, section, path) + case apimCSetVariable: + g.setVariable(n) + case apimCSendRequest, apimCSendOneWay: + g.sendRequest(n) + case apimCCacheLookupValue, apimCCacheStoreValue, apimCCacheRemoveValue: + g.cacheValue(n) + default: + if section == polInbound || section == polBackend { + g.execRequest(n) + } else { + g.execResponse(n) + } + } +} + +func (g *gwState) choose(n *polNode, section, path string) { + whens := 0 + + for _, w := range n.Kids { + if w.Name != apimCWhen { + continue + } + + whens++ + + g.cur = w + cond := g.boolAttr(w, apimCCondition, false) + + if g.evalErr != nil { + return + } + + if cond { + g.execList(w.Kids, section, path+apimPathSeparator+apimCWhen+"["+strconv.Itoa(whens)+"]") + + return + } + } + + if o := n.kid(apimCOtherwise); o != nil { + g.execList(o.Kids, section, path+apimPathSeparator+apimCOtherwise+"[1]") + } +} + +func (g *gwState) setVariable(n *polNode) { + v := g.subVal(n.Attrs[fieldValue]) + + if g.evalErr != nil { + return + } + + if s, ok := v.(string); ok && len(s) > apimMaxVarBytes { + g.evalErr = apimExprFail("the variable value is too large") + + return + } + + name := n.Attrs[fieldName] + if _, exists := g.vars[name]; !exists && len(g.vars) >= apimMaxVars { + g.evalErr = apimExprFail("too many context variables") + + return + } + + g.vars[name] = v +} + +// onError runs the on-error section after an error; the error response stays unless a policy replaces it. +func (g *gwState) onError(docs []*polNode) { + g.short, g.errored = false, true + + for _, n := range expandSection(docs, polOnError) { + g.cur, g.section = n, polOnError + g.execErrNode(n) + + if g.evalErr != nil { + g.evalErr = nil + + return + } + + if g.short { + return + } + } +} + +func (g *gwState) execErrNode(n *polNode) { + if g.respHeader == nil { + g.respHeader = http.Header{} + } + + g.errored = true + + g.execNodeInError(n) +} + +func (g *gwState) execNodeInError(n *polNode) { + g.cur = n + + switch n.Name { + case apimCChoose: + g.chooseErr(n) + default: + g.execNode(n, polOnError, "") + } +} + +func (g *gwState) chooseErr(n *polNode) { + for _, w := range n.Kids { + if w.Name == apimCWhen && g.boolAttr(w, apimCCondition, false) { + for _, k := range w.Kids { + g.execNodeInError(k) + + if g.short || g.evalErr != nil { + return + } + } + + return + } + } + + if o := n.kid(apimCOtherwise); o != nil { + for _, k := range o.Kids { + g.execNodeInError(k) + + if g.short || g.evalErr != nil { + return + } + } + } +} diff --git a/services/azurearm/rp_apim_import.go b/services/azurearm/rp_apim_import.go index 53a9762ccc..f8ec0da4ef 100644 --- a/services/azurearm/rp_apim_import.go +++ b/services/azurearm/rp_apim_import.go @@ -85,7 +85,7 @@ func parseAPISpec(format, value string) (*apimAPISpec, error) { for _, path := range keys { item := mapOf(paths[path]) - for _, method := range []string{"get", "put", "post", apimCDelete, "options", "head", "patch", "trace"} { + for _, method := range []string{apimMethodGet, "put", "post", apimCDelete, "options", "head", "patch", "trace"} { op := mapOf(item[method]) if op == nil { continue @@ -162,7 +162,7 @@ func buildImportedOp(method, path string, op map[string]any, used map[string]boo params := make([]any, 0, len(names)) for _, name := range names { - params = append(params, map[string]any{fieldName: name, "required": true, fieldType: "string"}) + params = append(params, map[string]any{fieldName: name, apimCRequired: true, fieldType: apxString}) } props[apimCTemplateParameters] = params diff --git a/services/azurearm/rp_apim_jwt.go b/services/azurearm/rp_apim_jwt.go new file mode 100644 index 0000000000..6710c5e3b5 --- /dev/null +++ b/services/azurearm/rp_apim_jwt.go @@ -0,0 +1,663 @@ +package azurearm + +import ( + "context" + "crypto/rsa" + "crypto/x509" + "encoding/base64" + "encoding/json/v2" + "errors" + "fmt" + "io" + "maps" + "math/big" + "net/http" + "slices" + "sort" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" +) + +const ( + apimJWTNone = "none" + apimMatchAny = "any" + apimCValidateJWT = "validate-jwt" + apimCOpenIDConfig = "openid-config" + apimCSigningKeys = "issuer-signing-keys" + apimCDecryptionKeys = "decryption-keys" + apimCAudiences = "audiences" + apimCIssuers = "issuers" + apimCRequiredClaims = "required-claims" + apimJWKSTTL = time.Hour + apimJWKSRetry = 5 * time.Minute + apimJWKSMaxEntries = 256 + apimJWKSMaxKeys = 64 + apimJWKSFetchTimeout = 10 * time.Second + apimJWKSMaxBytes = 1 << 20 + apimJWTMaxClockSkew = 24 * 60 * 60 + apimJWTMaxClaimValues = 256 +) + +var errAPIMJWKS = errors.New("openid configuration could not be retrieved") + +type gwJWTKey struct { + rsa *rsa.PublicKey + id string + sym []byte +} + +type apimJWKSEntry struct { + fetched, attempted time.Time + issuer string + keys []gwJWTKey + failed bool +} + +// apimJWKS caches OpenID configuration and signing keys per service and URL. +type apimJWKS struct { + mu *lockmetrics.RWMutex + m map[string]*apimJWKSEntry +} + +func newAPIMJWKS() *apimJWKS { + return &apimJWKS{mu: lockmetrics.New("azurearm.apim.jwks"), m: map[string]*apimJWKSEntry{}} +} + +func (j *apimJWKS) reset() { + j.mu.Lock("reset") + j.m = map[string]*apimJWKSEntry{} + j.mu.Unlock() +} + +func (j *apimJWKS) get(key string) (apimJWKSEntry, bool) { + j.mu.RLock("lookup") + defer j.mu.RUnlock() + + e := j.m[key] + if e == nil { + return apimJWKSEntry{}, false + } + + return *e, true +} + +func (j *apimJWKS) put(key string, e apimJWKSEntry) { + j.mu.Lock("put") + defer j.mu.Unlock() + + if _, ok := j.m[key]; !ok && len(j.m) >= apimJWKSMaxEntries { + for k := range j.m { + delete(j.m, k) + + break + } + } + + j.m[key] = &e +} + +type gwJWKDoc struct { + Keys []struct { + Kty string `json:"kty"` + Kid string `json:"kid"` + N string `json:"n"` + E string `json:"e"` + } `json:"keys"` +} + +func (g *gwState) fetchJSON(ctx context.Context, target string, out any) error { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) + if err != nil { + return err + } + + resp, err := g.p.client.Do(req) + if err != nil { + return err + } + + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("%w: status %d", errAPIMJWKS, resp.StatusCode) + } + + b, err := io.ReadAll(io.LimitReader(resp.Body, apimJWKSMaxBytes+1)) + if err != nil || len(b) > apimJWKSMaxBytes { + return errAPIMJWKS + } + + return json.Unmarshal(b, out, jsonx.V1()) +} + +func (g *gwState) loadJWKS(target string) (apimJWKSEntry, error) { + ctx, cancel := context.WithTimeout(g.r.Context(), apimJWKSFetchTimeout) + defer cancel() + + var cfg struct { + Issuer string `json:"issuer"` + JWKSURI string `json:"jwks_uri"` + } + + if err := g.fetchJSON(ctx, target, &cfg); err != nil || cfg.JWKSURI == "" { + return apimJWKSEntry{}, errAPIMJWKS + } + + var doc gwJWKDoc + if err := g.fetchJSON(ctx, cfg.JWKSURI, &doc); err != nil { + return apimJWKSEntry{}, errAPIMJWKS + } + + e := apimJWKSEntry{issuer: cfg.Issuer, fetched: g.now(), attempted: g.now()} + + for _, k := range doc.Keys { + if k.Kty != "RSA" || len(e.keys) >= apimJWKSMaxKeys { + continue + } + + if pk, ok := apimRSAKey(k.N, k.E); ok { + e.keys = append(e.keys, gwJWTKey{id: k.Kid, rsa: pk}) + } + } + + return e, nil +} + +func apimRSAKey(nb64, eb64 string) (*rsa.PublicKey, bool) { + nb, err1 := base64.RawURLEncoding.DecodeString(strings.TrimRight(nb64, "=")) + eb, err2 := base64.RawURLEncoding.DecodeString(strings.TrimRight(eb64, "=")) + + if err1 != nil || err2 != nil || len(nb) == 0 || len(eb) == 0 || len(eb) > 4 || len(nb) > 1024 { + return nil, false + } + + e := new(big.Int).SetBytes(eb) + if !e.IsInt64() || e.Int64() < 3 { + return nil, false + } + + return &rsa.PublicKey{N: new(big.Int).SetBytes(nb), E: int(e.Int64())}, true +} + +// openIDKeys returns the cached keys of an openid-config URL; a kid that the cache lacks forces a refresh at most +// every five minutes. +func (g *gwState) openIDKeys(target, kid string) (apimJWKSEntry, error) { + ck := apimKeyOf(g.plan.svcKey, target) + now := g.now() + + e, ok := g.p.jwks.get(ck) + if ok && e.failed { + if now.Sub(e.attempted) < apimJWKSRetry { + return apimJWKSEntry{}, errAPIMJWKS + } + + ok = false + } + + if ok && now.Sub(e.fetched) < apimJWKSTTL && + (kid == "" || jwkHas(e.keys, kid) || now.Sub(e.attempted) < apimJWKSRetry) { + return e, nil + } + + if ok && now.Sub(e.attempted) < apimJWKSRetry { + return e, nil + } + + fresh, err := g.loadJWKS(target) + if err != nil { + if ok { + e.attempted = now + g.p.jwks.put(ck, e) + + return e, nil + } + + g.p.jwks.put(ck, apimJWKSEntry{attempted: now, failed: true}) + + return apimJWKSEntry{}, err + } + + g.p.jwks.put(ck, fresh) + + return fresh, nil +} + +func jwkHas(keys []gwJWTKey, kid string) bool { + for _, k := range keys { + if k.id == kid { + return true + } + } + + return false +} + +func (g *gwState) jwtFail(n *polNode, reason, msg string) { + status := int(g.intAttr(n, "failed-validation-httpcode", http.StatusUnauthorized)) + if m, ok := n.Attrs["failed-validation-error-message"]; ok { + msg = g.sub(m) + } + + g.failR(status, reason, msg) +} + +func (g *gwState) jwtToken(n *polNode) (string, bool) { + switch { + case n.Attrs["header-name"] != "": + name := g.sub(n.Attrs["header-name"]) + v := strings.TrimSpace(g.header.Get(name)) + + if scheme := g.sub(n.Attrs["require-scheme"]); scheme != "" && strings.EqualFold(name, apimCAuthorizationX) { + pre, rest, _ := strings.Cut(v, " ") + if !strings.EqualFold(pre, scheme) { + return "", false + } + + return strings.TrimSpace(rest), true + } + + if strings.EqualFold(name, apimCAuthorizationX) { + if pre, rest, ok := strings.Cut(v, " "); ok && !strings.Contains(pre, ".") { + v = strings.TrimSpace(rest) + } + } + + return v, v != "" + case n.Attrs["query-parameter-name"] != "": + v := g.query.Get(g.sub(n.Attrs["query-parameter-name"])) + + return v, v != "" + } + + v, _ := g.subVal(n.Attrs["token-value"]).(string) + + return v, v != "" +} + +func (g *gwState) jwtKeys(n *polNode, kid string) ([]gwJWTKey, string, error) { + var ( + keys []gwJWTKey + issuer string + ) + + if sk := n.kid(apimCSigningKeys); sk != nil { + for _, k := range sk.Kids { + if jk, ok := g.policyKey(k); ok { + keys = append(keys, jk) + } + } + } + + for _, oc := range n.Kids { + if oc.Name != apimCOpenIDConfig { + continue + } + + e, err := g.openIDKeys(g.sub(oc.Attrs[apimCUrl]), kid) + if err != nil { + return nil, "", err + } + + keys, issuer = append(keys, e.keys...), e.issuer + } + + return keys, issuer, nil +} + +func (g *gwState) policyKey(k *polNode) (gwJWTKey, bool) { + id := g.sub(k.Attrs[apimCID]) + + if cid := k.Attrs[apimCCertID]; cid != "" { + c, found := g.plan.certs[strings.ToLower(g.sub(cid))] + if !found { + return gwJWTKey{}, false + } + + der, err := base64.StdEncoding.DecodeString(c.spki) + if err != nil { + return gwJWTKey{}, false + } + + pub, perr := x509.ParsePKIXPublicKey(der) + rk, isRSA := pub.(*rsa.PublicKey) + + return gwJWTKey{id: id, rsa: rk}, perr == nil && isRSA + } + + if k.Attrs["n"] != "" { + pk, ok := apimRSAKey(g.sub(k.Attrs["n"]), g.sub(k.Attrs["e"])) + + return gwJWTKey{id: id, rsa: pk}, ok + } + + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(g.sub(k.Text))) + if err != nil || len(raw) == 0 { + return gwJWTKey{}, false + } + + return gwJWTKey{id: id, sym: raw}, true +} + +func jwtMethods(unsigned bool) []string { + m := []string{"HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512"} + if unsigned { + m = append(m, apimJWTNone) + } + + return m +} + +func (g *gwState) validateJWT(n *polNode) { + raw, ok := g.jwtToken(n) + if !ok { + g.jwtFail(n, "TokenNotPresent", "JWT not present.") + + return + } + + signed := g.boolAttr(n, "require-signed-tokens", true) + skew := g.intAttr(n, "clock-skew", 0) + + if g.evalErr != nil || skew < 0 || skew > apimJWTMaxClockSkew { + g.evalErr = apimExprFail("clock-skew must be 0 to %d seconds", apimJWTMaxClockSkew) + + return + } + + opts := []jwt.ParserOption{ + jwt.WithValidMethods(jwtMethods(!signed)), jwt.WithLeeway(time.Duration(skew) * time.Second), + jwt.WithTimeFunc(g.now), + } + if g.boolAttr(n, "require-expiration-time", true) { + opts = append(opts, jwt.WithExpirationRequired()) + } + + parser := jwt.NewParser(opts...) + + var hdr struct{ Kid string } + + if tok, _, err := jwt.NewParser().ParseUnverified(raw, jwt.MapClaims{}); err == nil { + hdr.Kid, _ = tok.Header["kid"].(string) + } + + keys, issuer, err := g.jwtKeys(n, hdr.Kid) + if err != nil { + g.jwtFail(n, "JwtInvalid", "The OpenID configuration could not be retrieved. Access denied.") + + return + } + + claims := jwt.MapClaims{} + tok, perr := g.parseWithKeys(parser, raw, claims, keys, hdr.Kid, signed) + + if perr != nil { + g.jwtParseFail(n, perr) + + return + } + + if !g.jwtClaims(n, claims, issuer) { + return + } + + if v := n.Attrs["output-token-variable-name"]; v != "" { + g.vars[v] = &apimExprJWT{claims: claims, alg: tok.Method.Alg()} + } +} + +func (g *gwState) parseWithKeys( + p *jwt.Parser, raw string, claims jwt.MapClaims, keys []gwJWTKey, kid string, signed bool, +) (*jwt.Token, error) { + cands := make([]gwJWTKey, 0, len(keys)) + + for _, k := range keys { + if kid == "" || k.id == "" || k.id == kid { + cands = append(cands, k) + } + } + + if len(cands) == 0 { + cands = keys + } + + last := jwt.ErrTokenUnverifiable + + for _, k := range cands { + c := jwt.MapClaims{} + + tok, err := p.ParseWithClaims(raw, c, func(t *jwt.Token) (any, error) { return jwtKeyFor(t, k, signed) }) + if err == nil { + maps.Copy(claims, c) + + return tok, nil + } + + if !errors.Is(err, jwt.ErrTokenSignatureInvalid) && !errors.Is(err, jwt.ErrTokenUnverifiable) { + return nil, err + } + + last = err + } + + if !signed && len(cands) == 0 { + c := jwt.MapClaims{} + + if tok, err := p.ParseWithClaims( + raw, + c, + func(*jwt.Token) (any, error) { return jwt.UnsafeAllowNoneSignatureType, nil }, + ); err == nil { + maps.Copy(claims, c) + + return tok, nil + } + } + + return nil, last +} + +// jwtKeyFor binds an algorithm family to a key type, so an HS* token can never verify against an RSA key. +func jwtKeyFor(t *jwt.Token, k gwJWTKey, signed bool) (any, error) { + switch t.Method.(type) { + case *jwt.SigningMethodHMAC: + if k.sym != nil { + return k.sym, nil + } + case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS: + if k.rsa != nil { + return k.rsa, nil + } + } + + if t.Method.Alg() == apimJWTNone && !signed { + return jwt.UnsafeAllowNoneSignatureType, nil + } + + return nil, jwt.ErrTokenUnverifiable +} + +func (g *gwState) jwtParseFail(n *polNode, err error) { + switch { + case errors.Is(err, jwt.ErrTokenExpired): + g.jwtFail(n, "TokenExpired", "IDX10223: Lifetime validation failed. The token is expired. Access denied.") + case errors.Is(err, jwt.ErrTokenSignatureInvalid): + g.jwtFail(n, "TokenSignatureInvalid", "IDX10503: Signature validation failed. Access denied.") + case errors.Is(err, jwt.ErrTokenUnverifiable): + g.jwtFail( + n, + "TokenSignatureKeyNotFound", + "IDX10500: Signature validation failed. No security keys were provided. Access denied.", + ) + case errors.Is(err, jwt.ErrTokenRequiredClaimMissing): + g.jwtFail(n, "JwtInvalid", "IDX10225: The token has no expiration time.") + case errors.Is(err, jwt.ErrTokenMalformed): + g.jwtFail(n, "JwtInvalid", "IDX14100: JWT is not well formed. Access denied.") + default: + g.jwtFail(n, "JwtInvalid", "The token could not be validated. Access denied.") + } +} + +func apimClaimValues(v any, sep string) []string { + switch t := v.(type) { + case string: + if sep != "" { + return strings.Split(t, sep) + } + + return []string{t} + case []any: + out := make([]string, 0, len(t)) + + for _, e := range t { + out = append(out, apimExprString(apimClaimScalar(e))) + } + + return out + } + + return []string{apimExprString(apimClaimScalar(v))} +} + +func apimClaimScalar(v any) any { + if f, ok := v.(float64); ok && f == float64(int64(f)) { + return int64(f) + } + + return v +} + +func (g *gwState) jwtClaims(n *polNode, claims jwt.MapClaims, openIDIssuer string) bool { + if a := n.kid(apimCAudiences); a != nil { + allowed, have := g.subAll(a.values(apimCAudience)), nonEmpty(apimClaimValues(claims["aud"], "")) + if !anyIn(have, allowed) { + g.jwtFail(n, "TokenAudienceNotAllowed", "IDX10214: Audience validation failed. Audiences: '"+ + strings.Join(have, ", ")+"'. Did not match one of the valid audiences. Access denied.") + + return false + } + } + + iss, _ := claims["iss"].(string) + issuers := []string(nil) + + if i := n.kid(apimCIssuers); i != nil { + issuers = g.subAll(i.values(apimCIssuer)) + } else if openIDIssuer != "" { + issuers = []string{openIDIssuer} + } + + if issuers != nil && (iss == "" || !anyIn([]string{iss}, issuers)) { + g.jwtFail(n, "TokenIssuerNotAllowed", "IDX10205: Issuer validation failed. Issuer: '"+iss+ + "'. Did not match one of the valid issuers. Access denied.") + + return false + } + + return g.requiredClaims(n, claims) +} + +func nonEmpty(in []string) []string { + return slices.DeleteFunc(in, func(s string) bool { return s == "" }) +} + +func anyIn(have, allowed []string) bool { + for _, h := range have { + if slices.Contains(allowed, h) { + return true + } + } + + return false +} + +func (g *gwState) requiredClaims(n *polNode, claims jwt.MapClaims) bool { + rc := n.kid(apimCRequiredClaims) + if rc == nil { + return true + } + + var missing []string + + for _, c := range rc.Kids { + if _, ok := claims[c.Attrs[fieldName]]; !ok { + missing = append(missing, c.Attrs[fieldName]) + } + } + + if len(missing) > 0 { + sort.Strings(missing) + g.jwtFail( + n, + "TokenClaimNotFound", + "JWT is missing the following claims: "+strings.Join(missing, ", ")+". Access denied.", + ) + + return false + } + + for _, c := range rc.Kids { + want := g.subAll(c.values(fieldValue)) + if len(want) == 0 || len(want) > apimJWTMaxClaimValues { + continue + } + + have := apimClaimValues(claims[c.Attrs[fieldName]], c.Attrs["separator"]) + + okAll := true + for _, w := range want { + okAll = okAll && anyIn([]string{w}, have) + } + + if (c.Attrs["match"] == apimMatchAny && anyIn(have, want)) || (c.Attrs["match"] != apimMatchAny && okAll) { + continue + } + + g.jwtFail(n, "TokenClaimValueNotAllowed", "Claim "+c.Attrs[fieldName]+" value of "+strings.Join(have, ",")+ + " is not allowed. Access denied.") + + return false + } + + return true +} + +// apimExprJWT is the Jwt object of the policy expressions reference. +type apimExprJWT struct { + claims jwt.MapClaims + alg string +} + +func (j *apimExprJWT) member(name string) (any, error) { + switch name { + case "Claims": + return &apimExprDict{get: func(k string) (any, bool) { + v, ok := j.claims[k] + if !ok { + return nil, false + } + + return apimClaimValues(v, ""), true + }}, nil + case "Issuer": + s, _ := j.claims["iss"].(string) + + return s, nil + case "Subject": + s, _ := j.claims["sub"].(string) + + return s, nil + case "Algorithm": + return j.alg, nil + case apxID: + s, _ := j.claims["jti"].(string) + + return s, nil + } + + return nil, apimExprFail("Jwt.%s is not supported", name) +} diff --git a/services/azurearm/rp_apim_mgmt.go b/services/azurearm/rp_apim_mgmt.go new file mode 100644 index 0000000000..b2b7cbc815 --- /dev/null +++ b/services/azurearm/rp_apim_mgmt.go @@ -0,0 +1,596 @@ +package azurearm + +import ( + "crypto/sha1" //nolint:gosec // the certificate thumbprint is a SHA-1 fingerprint by definition + "crypto/x509" + "encoding/base64" + "encoding/hex" + "encoding/json/jsontext" + "encoding/json/v2" + "encoding/pem" + "encoding/xml" + "errors" + "io" + "mime" + "net/http" + "net/url" + "slices" + "sort" + "strconv" + "strings" + "time" + + "software.sslmate.com/src/go-pkcs12" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" +) + +const ( + apimVerbError = "error" + apimCorrNone = "None" + apimCertificatesType = "certificates" + apimDiagnosticsType = "diagnostics" + apimGlobalSchemasType = "schemas" + apimAPIDiagType = "apis/diagnostics" + apimAPISchemasType = "apis/schemas" + apimAPIReleasesType = "apis/releases" + apimMaxCertificates = 100 + apimMaxCertBytes = 1 << 20 + apimMaxSchemaBytes = 4 << 20 + apimMaxNotes = 500 + apimMaxLoggedHeaders = 100 + apimMaxDiagBytes = 8192 + apimMaxSchemas = 1000 + apimMasterSub = "master" + apimRevMarker = ";rev=" + apimMaxRevision = 1000 + apimCurrent = "isCurrent" + apimRevision = "apiRevision" + apimRevCreated = "createdDateTime" + apimRevUpdated = "updatedDateTime" +) + +func apimMgmtKinds() []apimKind { + mk := func(typ string, norm func(*apimService, string, string, map[string]any, *apimEntity) (map[string]any, error), + view func(map[string]any) map[string]any, + ) apimKind { + return apimKind{typ: typ, norm: norm, view: view, store: func(s *apimService) map[string]*apimEntity { + if s.Generic == nil { + s.Generic = map[string]map[string]*apimEntity{} + } + + if s.Generic[typ] == nil { + s.Generic[typ] = map[string]*apimEntity{} + } + + return s.Generic[typ] + }} + } + + return []apimKind{ + mk(apimCertificatesType, normCertificate, dropSecrets("data", "password", "publicKey", "privateKey")), + mk(apimDiagnosticsType, normDiagnostic, nil), + mk(apimAPIDiagType, normDiagnostic, nil), + mk(apimGlobalSchemasType, normGlobalSchema, nil), + mk(apimAPISchemasType, normAPISchema, nil), + mk(apimAPIReleasesType, normRelease, nil), + } +} + +func apimMgmtKind(typ string) apimKind { + for _, k := range apimMgmtKinds() { + if k.typ == typ { + return k + } + } + + return apimKind{} +} + +// ensureAPIMSystemEntities adds the built-in groups and the all-access master subscription when absent; entities +// that exist, user-created ones included, are left alone. +func ensureAPIMSystemEntities(s *apimService, now time.Time) { + if s.Generic == nil { + s.Generic = map[string]map[string]*apimEntity{} + } + + if s.Generic[apimGroupsType] == nil { + s.Generic[apimGroupsType] = map[string]*apimEntity{} + } + + for _, g := range apimMgmtGroups() { + if s.Generic[apimGroupsType][entKey("", g.id)] != nil { + continue + } + + s.Generic[apimGroupsType][entKey("", g.id)] = &apimEntity{ID: g.id, Etag: 1, Props: map[string]any{ + apimCDisplayName: g.name, webDescription: g.desc, fieldType: "system", "builtIn": true, + }} + } + + if s.Subs[entKey("", apimMasterSub)] != nil { + return + } + + stamp := now.UTC().Format(time.RFC3339) + scope, _ := s.normScope("/") + + s.Subs[entKey("", apimMasterSub)] = &apimEntity{ID: apimMasterSub, Etag: 1, Props: map[string]any{ + apimCDisplayName: "Built-in all-access subscription", acrPropScope: scope, sqlPropState: apimStateActive, + redisPropPrimaryKey: newAPIMKey(), redisPropSecondaryKey: newAPIMKey(), "allowTracing": true, + apimCCreatedDate: stamp, apimCStartDate: stamp, + }} +} + +// seedAPIMBuiltins creates the entities a new service starts with: the built-in groups, the all-access master +// subscription and, on the classic tiers, the Starter and Unlimited products. +func seedAPIMBuiltins(s *apimService, now time.Time) { + ensureAPIMSystemEntities(s, now) + + if s.SKU == apimSKUConsumption { + return + } + + for _, p := range []struct { + id, name, desc string + policy string + approval bool + }{ + { + id: "starter", name: "Starter", + desc: "Subscribers will be able to run 5 calls/minute up to a maximum of 100 calls/week.", + policy: `` + + `` + + ``, + }, + { + id: "unlimited", name: "Unlimited", approval: true, + desc: "Subscribers have completely unlimited access to the API. Administrator approval is required.", + }, + } { + s.Products[entKey("", p.id)] = &apimEntity{ID: p.id, Etag: 1, Props: map[string]any{ + apimCDisplayName: p.name, + webDescription: p.desc, + sqlPropState: "published", + apimCSubscriptionRequired: true, + "approvalRequired": p.approval, + "subscriptionsLimit": 1, + }} + + if p.policy != "" { + s.Policies[entKey("products/"+p.id, apimPolicyID)] = &apimEntity{ + ID: apimPolicyID, Etag: 1, Props: map[string]any{apimCFormat: apimFormatXML, fieldValue: p.policy}, + } + } + + for _, g := range []string{"administrators", "developers"} { + s.Links[apimLinkKey(apimLinkProductGroup, p.id, g)] = true + } + } +} + +type apimBuiltinGroup struct{ id, name, desc string } + +func apimMgmtGroups() []apimBuiltinGroup { + return []apimBuiltinGroup{ + { + "administrators", "Administrators", + "Administrators is a built-in group containing the admin email account provided at the time of " + + "service creation. Its membership is managed by the system.", + }, + { + "developers", + "Developers", + "Developers is a built-in group. Its membership is managed by the system. Signed-in users fall into this group.", + }, + { + "guests", "Guests", + "Guests is a built-in group. Its membership is managed by the system. " + + "Unauthenticated users visiting the developer portal fall into this group.", + }, + } +} + +func delBuiltinSub(_ *apimService, _, id string, _ url.Values) error { + if strings.EqualFold(id, apimMasterSub) { + return apimInvalid("The built-in all-access subscription cannot be deleted.") + } + + return nil +} + +func delSystemGroup(s *apimService, _, id string, _ url.Values) error { + if g := s.Generic[apimGroupsType][entKey("", id)]; g != nil && strOf(g.Props, fieldType) == "system" { + return apimInvalid("The system group '%s' cannot be deleted.", id) + } + + return nil +} + +func apimParseCert(raw []byte, password string) (*x509.Certificate, error) { + if _, cert, _, err := pkcs12.DecodeChain(raw, password); err == nil && cert != nil { + return cert, nil + } + + if cert, err := x509.ParseCertificate(raw); err == nil { + return cert, nil + } + + if blk, _ := pem.Decode(raw); blk != nil && blk.Type == "CERTIFICATE" { + return x509.ParseCertificate(blk.Bytes) + } + + return nil, apimInvalid("The certificate data is not a valid PFX (with its password) or X.509 certificate.") +} + +func normCertificate(s *apimService, _, _ string, in map[string]any, prev *apimEntity) (map[string]any, error) { + out := cloneAnyMap(in) + + if prev == nil && len(s.Generic[apimCertificatesType]) >= apimMaxCertificates { + return nil, apimErr( + http.StatusConflict, + apimCodeConflict, + "The service already has %d certificates.", + apimMaxCertificates, + ) + } + + if _, has := out["keyVault"]; has { + return nil, apimInvalid("Key Vault certificates are not supported; upload the certificate data.") + } + + data, err := optString(out, "data", 1, apimMaxCertBytes, true, "certificate data") + if err != nil { + return nil, err + } + + raw, derr := base64.StdEncoding.DecodeString(data) + if derr != nil { + return nil, apimInvalid("The certificate data is not valid Base64.") + } + + pw, err := optString(out, "password", 0, apimMaxName, false, "certificate password") + if err != nil { + return nil, err + } + + cert, err := apimParseCert(raw, pw) + if err != nil { + return nil, err + } + + _, hasKey := apimTLSFromPFX(raw, pw) + out["privateKey"] = hasKey + + sum := sha1.Sum(cert.Raw) //nolint:gosec // see import + + out["subject"] = cert.Subject.String() + out["thumbprint"] = strings.ToUpper(hex.EncodeToString(sum[:])) + out["expirationDate"] = cert.NotAfter.UTC().Format(time.RFC3339) + out["publicKey"] = base64.StdEncoding.EncodeToString(cert.RawSubjectPublicKeyInfo) + + return out, nil +} + +func apimEnum(in map[string]any, key string, allowed ...string) error { + if v, has := in[key]; has && v != nil { + s, _ := v.(string) + if !containsStr(allowed, s) { + return apimInvalid("The %s '%v' is not valid; allowed values are %s.", key, v, strings.Join(allowed, ", ")) + } + } + + return nil +} + +func containsStr(list []string, v string) bool { + return slices.Contains(list, v) +} + +func normDiagnostic(s *apimService, _, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { + out := cloneAnyMap(in) + + logger, err := optString(out, "loggerId", 1, apimMaxURL, true, "diagnostic loggerId") + if err != nil { + return nil, err + } + + id := logger[strings.LastIndex(logger, "/")+1:] + if !strings.Contains(strings.ToLower(logger), "/loggers/") || s.Generic[apimLoggersType][entKey("", id)] == nil { + return nil, apimInvalid("The loggerId '%s' does not reference an existing logger.", logger) + } + + if err = normDiagnosticFields(out); err != nil { + return nil, err + } + + for _, side := range []string{"frontend", "backend"} { + if err = normPipelineSettings(mapOf(out[side])); err != nil { + return nil, err + } + } + + return out, nil +} + +func normDiagnosticFields(out map[string]any) error { + for key, allowed := range map[string][]string{ + "alwaysLog": {"allErrors"}, "verbosity": {"verbose", "information", apimVerbError}, + "httpCorrelationProtocol": {apimCorrNone, "Legacy", "W3C"}, "operationNameFormat": {"Name", "Url"}, + } { + if err := apimEnum(out, key, allowed...); err != nil { + return err + } + } + + for _, b := range []string{"logClientIp", "metrics"} { + if _, err := optBool(out, b, false); err != nil { + return err + } + } + + sm := mapOf(out["sampling"]) + if sm == nil { + return nil + } + + if err := apimEnum(sm, "samplingType", "fixed"); err != nil { + return err + } + + if p, has := sm["percentage"]; has { + f, ok := p.(float64) + if !ok || f < 0 || f > 100 { + return apimInvalid("The sampling percentage must be a number from 0 to 100.") + } + } + + return nil +} + +func normPipelineSettings(side map[string]any) error { + for _, dir := range []string{apimKindRequest, apimKindResponse} { + d := mapOf(side[dir]) + if d == nil { + continue + } + + if h := anySlice(mapOf(d)["headers"]); len(h) > apimMaxLoggedHeaders { + return apimInvalid("At most %d headers can be logged.", apimMaxLoggedHeaders) + } + + if b := mapOf(d["body"]); b != nil { + if n, has := b["bytes"]; has { + f, ok := n.(float64) + if !ok || f < 0 || f > apimMaxDiagBytes { + return apimInvalid("The logged body bytes must be 0 to %d.", apimMaxDiagBytes) + } + } + } + } + + return nil +} + +func apimJSONOK(v any) bool { + switch t := v.(type) { + case nil: + return false + case string: + return jsontext.Value(t).IsValid() + } + + b, err := json.Marshal(v, jsonx.V1()) + + return err == nil && len(b) <= apimMaxSchemaBytes +} + +func normGlobalSchema(s *apimService, _, _ string, in map[string]any, prev *apimEntity) (map[string]any, error) { + out := cloneAnyMap(in) + + typ, err := apimOneOf(out, "schemaType", "schema type", apimFormatXML, "json") + if err != nil { + return nil, err + } + + if prev == nil && len(s.Generic[apimGlobalSchemasType]) >= apimMaxSchemas { + return nil, apimErr( + http.StatusConflict, + apimCodeConflict, + "The service already has %d schemas.", + apimMaxSchemas, + ) + } + + if _, err = optString(out, webDescription, 0, apimMaxText, false, "schema description"); err != nil { + return nil, err + } + + val, doc := out[fieldValue], out["document"] + + switch { + case val == nil && doc == nil: + return nil, apimInvalid("The schema needs a value or a document.") + case typ == apimFormatXML: + str, ok := val.(string) + if !ok || len(str) > apimMaxSchemaBytes || apimXMLOK(str) != nil { + return nil, apimInvalid("An xml schema value must be a well-formed XML string.") + } + case !apimJSONOK(firstAny(val, doc)): + return nil, apimInvalid("A json schema must be valid JSON.") + } + + return out, nil +} + +func firstAny(a, b any) any { + if a != nil { + return a + } + + return b +} + +func normAPISchema(_ *apimService, _, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { + out := cloneAnyMap(in) + + ct, err := optString(out, apimCContentTypeX, 1, apimMaxName, true, "schema contentType") + if err != nil { + return nil, err + } + + mt, _, merr := mime.ParseMediaType(ct) + if merr != nil || !strings.Contains(mt, "/") { + return nil, apimInvalid("The schema contentType '%s' is not a valid media type.", ct) + } + + doc := mapOf(out["document"]) + if len(doc) == 0 { + return nil, apimInvalid("The schema document is required.") + } + + body := firstAny(firstAny(doc[fieldValue], doc["components"]), doc["definitions"]) + + switch { + case body == nil: + return nil, apimInvalid("The schema document needs a value, components or definitions.") + case strings.HasSuffix(mt, "+xml") || mt == "application/xml": + if str, ok := body.(string); !ok || apimXMLOK(str) != nil { + return nil, apimInvalid("An XML schema document must be well-formed XML.") + } + case strings.HasSuffix(mt, "json") && !apimJSONOK(body): + return nil, apimInvalid("A JSON schema document must be valid JSON.") + } + + return out, nil +} + +// apiBaseID strips the ;rev=N suffix of a revision identifier. +func apiBaseID(id string) string { + base, _, _ := strings.Cut(id, apimRevMarker) + + return base +} + +func apiRevisionOf(id string) (string, bool, error) { + _, rev, has := strings.Cut(id, apimRevMarker) + if !has { + return "1", false, nil + } + + n, err := strconv.Atoi(rev) + if err != nil || n < 1 || n > apimMaxRevision { + return "", true, apimInvalid("The revision of '%s' must be a number from 1 to %d.", id, apimMaxRevision) + } + + return strconv.Itoa(n), true, nil +} + +func normRelease(s *apimService, parent, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { + out := cloneAnyMap(in) + + ref, err := optString(out, "apiId", 1, apimMaxURL, true, "release apiId") + if err != nil { + return nil, err + } + + target := ref[strings.LastIndex(ref, "/")+1:] + if !strings.EqualFold(apiBaseID(target), apiBaseID(parent)) || s.APIs[entKey("", target)] == nil { + return nil, apimInvalid("The apiId '%s' must reference an existing revision of the API '%s'.", ref, parent) + } + + if _, err = optString(out, "notes", 0, apimMaxNotes, false, "release notes"); err != nil { + return nil, err + } + + stamp := apimNow(s).UTC().Format(time.RFC3339) + out[apimCCreatedDate], out["updatedDateTime"] = stamp, stamp + + for _, a := range s.APIs { + if strings.EqualFold(apiBaseID(a.ID), apiBaseID(parent)) { + a.Props[apimCurrent] = strings.EqualFold(a.ID, target) + a.Etag++ + } + } + + return out, nil +} + +func apimNow(s *apimService) time.Time { + if s.now != nil { + return s.now() + } + + return time.Now() +} + +// apiRevisions lists the revisions of an API as ApiRevisionContract values. +func (s *apimService) apiRevisions(id string) []map[string]any { + var out []map[string]any + + for _, a := range s.APIs { + if !strings.EqualFold(apiBaseID(a.ID), apiBaseID(id)) { + continue + } + + cur, _ := a.Props[apimCurrent].(bool) + out = append(out, map[string]any{ + "apiId": "/apis/" + a.ID, apimRevision: strOf(a.Props, apimRevision), "isOnline": true, apimCurrent: cur, + apimFieldDesc: strOf(a.Props, "apiRevisionDescription"), "createdDateTime": strOf(a.Props, apimRevCreated), + "updatedDateTime": strOf(a.Props, apimRevUpdated), + }) + } + + sort.Slice(out, func(i, j int) bool { + ri, _ := strconv.Atoi(strOf(out[i], apimRevision)) + rj, _ := strconv.Atoi(strOf(out[j], apimRevision)) + + return ri < rj + }) + + return out +} + +func (p *APIMProvider) apiRevisionList(s *apimService, req apimReq) (apimResp, error) { + if req.Method != http.MethodGet { + return apimResp{}, apimErr(http.StatusMethodNotAllowed, apimCMethodNotAllowed, "Method not allowed.") + } + + if _, ok := s.APIs[entKey("", req.Rest[1])]; !ok { + return apimResp{}, apimNotFound(apimCAPI) + } + + return apimResp{Status: http.StatusOK, Body: map[string]any{fieldValue: s.apiRevisions(req.Rest[1])}}, nil +} + +func apimXMLOK(doc string) error { + dec := xml.NewDecoder(strings.NewReader(doc)) + dec.Strict = true + + seen := false + + for { + tok, err := dec.Token() + if errors.Is(err, io.EOF) { + break + } + + if err != nil { + return err + } + + if _, ok := tok.(xml.StartElement); ok { + seen = true + } + + if _, ok := tok.(xml.Directive); ok { + return errAPIMFragmentRoot + } + } + + if !seen { + return errAPIMFragmentRoot + } + + return nil +} diff --git a/services/azurearm/rp_apim_more.go b/services/azurearm/rp_apim_more.go index dd0f73c0dd..5c715c8996 100644 --- a/services/azurearm/rp_apim_more.go +++ b/services/azurearm/rp_apim_more.go @@ -50,6 +50,20 @@ func apimGenericKinds() []apimKind { }} } + kinds := apimGenericKindList(mk) + for i := range kinds { + if kinds[i].typ == apimGroupsType { + kinds[i].del = delSystemGroup + } + } + + return append(kinds, apimMgmtKinds()...) +} + +func apimGenericKindList( + mk func(string, func(*apimService, string, string, map[string]any, *apimEntity) (map[string]any, error), + func(map[string]any) map[string]any) apimKind, +) []apimKind { return []apimKind{ mk(apimTagsType, normTag, nil), mk(apimGroupsType, normGroup, nil), mk(apimLoggersType, normLogger, viewLogger), mk(apimCachesType, normCache, nil), @@ -123,11 +137,11 @@ func normGroup(_ *apimService, _, _ string, in map[string]any, prev *apimEntity) out[fieldType] = prev.Props[fieldType] case typ == "": out[fieldType] = apimGroupCustom - case typ != apimGroupCustom && typ != "external": + case typ != apimGroupCustom && typ != apimCExternal: return nil, apimInvalid("The group type '%s' is not valid; allowed values are custom and external.", typ) } - if strOf(out, "externalId") != "" && strOf(out, fieldType) != "external" { + if strOf(out, "externalId") != "" && strOf(out, fieldType) != apimCExternal { return nil, apimInvalid("The externalId applies to external groups only.") } @@ -349,7 +363,7 @@ func normVersionSet(_ *apimService, _, _ string, in map[string]any, _ *apimEntit return out, nil } -func normFragment(_ *apimService, _, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { +func normFragment(s *apimService, _, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { out := cloneAnyMap(in) format := strOf(out, apimCFormat) @@ -370,6 +384,10 @@ func normFragment(_ *apimService, _, _ string, in map[string]any, _ *apimEntity) return nil, apimInvalid("The policy fragment is not well-formed XML: %v.", err) } + if err = validateFragment(s, doc); err != nil { + return nil, err + } + out[apimCFormat] = format return out, nil diff --git a/services/azurearm/rp_apim_persist.go b/services/azurearm/rp_apim_persist.go index 78de90fbb2..c12302f3ad 100644 --- a/services/azurearm/rp_apim_persist.go +++ b/services/azurearm/rp_apim_persist.go @@ -65,6 +65,7 @@ func (p *APIMProvider) restore(snap *apimSnapshot) { s.now = p.now ensureAPIMMaps(s) + ensureAPIMSystemEntities(s, p.now()) p.svcs[k] = s } } diff --git a/services/azurearm/rp_apim_policy.go b/services/azurearm/rp_apim_policy.go index 3744aa2f0a..9684baea9f 100644 --- a/services/azurearm/rp_apim_policy.go +++ b/services/azurearm/rp_apim_policy.go @@ -99,7 +99,7 @@ func (pp *polParser) start(d *xml.Decoder, t xml.StartElement) error { } func parsePolicy(doc, scope string) (*polNode, error) { - d := xml.NewDecoder(strings.NewReader(doc)) + d := xml.NewDecoder(strings.NewReader(apimEscapeExpressions(doc))) pp := &polParser{scope: scope} for { @@ -156,7 +156,7 @@ func polSpecOf(name string) (polSpec, bool) { case apimCSetQueryParameter: return polSpec{ attrs: []string{fieldName, apimCExistsAction}, required: []string{fieldName}, kids: []string{fieldValue}, - sections: []string{polInbound, polBackend, polOnError}, + sections: []string{polInbound, polBackend}, }, true case "rewrite-uri": return polSpec{ @@ -165,12 +165,13 @@ func polSpecOf(name string) (polSpec, bool) { }, true case apimCReturnResponse: return polSpec{ - attrs: []string{"response-variable-name"}, kids: []string{apimCSetStatus, apimCSetHeader, apimCSetBody}, + attrs: []string{apimCRespVar}, kids: []string{apimCSetStatus, apimCSetHeader, apimCSetBody}, sections: allSections(), }, true case apimCMockResponse: return polSpec{ - attrs: []string{apimCStatusCodeX, "content-type"}, sections: []string{polInbound, polOutbound}, + attrs: []string{apimCStatusCodeX, "content-type"}, + sections: []string{polInbound, polOutbound, polOnError}, }, true case apimCRateLimit: return polSpec{ @@ -210,7 +211,7 @@ func polSpecOf(name string) (polSpec, bool) { }, true } - return polSpec{}, false + return extPolSpec(name) } func polNestedSpec(name string) (polSpec, bool) { @@ -237,7 +238,7 @@ func polNestedSpec(name string) (polSpec, bool) { return polSpec{kids: []string{apimCHeader}}, true } - return polSpec{}, false + return extNestedSpec(name) } // validatePolicy checks a policy document against the supported subset and the service's named values and @@ -285,21 +286,74 @@ func validateStatement(s *apimService, n *polNode, section string) error { return polErr(n, "The policy element is not supported by this API Management gateway.") } - if !slices.Contains(spec.sections, section) { + if section != apimSectionAny && !slices.Contains(spec.sections, section) { return polErr(n, "The policy element is not allowed in the %s section.", section) } - if section == polOnError && n.Name != polBase { - return polErr(n, "Policies in the on-error section are not executed by this API Management gateway.") - } - if n.Name == apimCRateLimit && n.Scope == "svc|" { return polErr(n, "The rate-limit policy can be used at the product, API and operation scopes only.") } + if n.Name == apimCChoose { + return validateChoose(s, n, section) + } + return validateElement(s, n, spec) } +func validateChoose(s *apimService, n *polNode, section string) error { + if err := validateAttrs(s, n, polSpec{}); err != nil { + return err + } + + whens := 0 + + for i, k := range n.Kids { + switch { + case k.Name == apimCWhen && whens == i: + whens++ + case k.Name == apimCOtherwise && i == len(n.Kids)-1 && whens > 0: + default: + return polErr(k, "The choose policy takes when elements followed by at most one otherwise element.") + } + + if err := validateChooseBranch(s, k, section); err != nil { + return err + } + } + + if whens == 0 { + return polErr(n, "The choose policy needs at least one when element.") + } + + return nil +} + +func validateChooseBranch(s *apimService, k *polNode, section string) error { + ks, _ := polNestedSpec(k.Name) + if err := validateAttrs(s, k, ks); err != nil { + return err + } + + if c, has := k.Attrs[apimCCondition]; has { + if _, expr, _ := apimIsExprText(c); !expr && c != cmpTrue && c != apimCFalse { + return polErr(k, "The condition must be a boolean expression or constant.") + } + } + + for _, st := range k.Kids { + if st.Name == polBase { + return polErr(st, "The base element is not allowed inside choose.") + } + + if err := validateStatement(s, st, section); err != nil { + return err + } + } + + return nil +} + func validateElement(s *apimService, n *polNode, spec polSpec) error { if err := validateAttrs(s, n, spec); err != nil { return err @@ -329,7 +383,7 @@ func validateElement(s *apimService, n *polNode, spec polSpec) error { func validateAttrs(s *apimService, n *polNode, spec polSpec) error { for name, v := range n.Attrs { - if !slices.Contains(spec.attrs, name) { + if !slices.Contains(spec.attrs, name) && name != apimCID { return polErr(n, "The attribute '%s' is not supported.", name) } @@ -356,8 +410,14 @@ func validateText(s *apimService, n *polNode) error { } func checkPolicyText(s *apimService, n *polNode, v string) error { - if t := strings.TrimSpace(v); strings.HasPrefix(t, "@(") || strings.HasPrefix(t, "@{") { - return polErr(n, "Policy expressions are not supported.") + if body, expr, multi := apimIsExprText(v); expr { + if _, err := apimParseExpr(body); err != nil { + return polErr(n, "The policy expression is not supported by this API Management gateway: %v.", err) + } + + return nil + } else if multi { + return polErr(n, "Multi-statement policy expressions (@{...}) are not supported.") } for _, m := range apimNamedRefRE.FindAllStringSubmatch(v, -1) { @@ -419,7 +479,7 @@ func validateSemantics(s *apimService, n *polNode) error { return validateBackendTarget(s, n) } - return nil + return validateExt(s, n) } func validateCheckHeader(n *polNode) error { @@ -484,11 +544,11 @@ func validateBackendTarget(s *apimService, n *polNode) error { func normPolicy(s *apimService, parent, _ string, in map[string]any, _ *apimEntity) (map[string]any, error) { format := strOf(in, apimCFormat) if format == "" { - format = "xml" + format = apimFormatXML } switch format { - case "xml", apimCRawxml: + case apimFormatXML, apimCRawxml: case "xml-link", "rawxml-link": return nil, apimInvalid("Policies cannot be imported from a link; supply the document inline.") default: diff --git a/services/azurearm/rp_apim_policy_ext.go b/services/azurearm/rp_apim_policy_ext.go new file mode 100644 index 0000000000..9e46f55425 --- /dev/null +++ b/services/azurearm/rp_apim_policy_ext.go @@ -0,0 +1,589 @@ +package azurearm + +import ( + "encoding/base64" + "errors" + "math" + "slices" + "strings" +) + +const ( + apimCThumbprint = "thumbprint" + apimCUsername = "username" + apimCRespVar = "response-variable-name" + apimCPasswordAttr = "password" + apimCCertID = "certificate-id" + apimCIssuer = "issuer" + apimCMode = "mode" + apimCBodyAttr = "body" + apimCAudience = "audience" + apimCExternal = "external" + apimModeCopy = "copy" + apimCIncludeFragment = "include-fragment" + apimSectionAny = "*" + apimFragLineShift = 16 + apimMaxVariableName = 128 + apimProductPolicyIdx = 2 +) + +// extPolSpec holds the statements of the control-flow, throttling, caching, send and JWT policies. +func extPolSpec(name string) (polSpec, bool) { + if sp, ok := extPolSpecFlow(name); ok { + return sp, true + } + + return extPolSpecCache(name) +} + +func extPolSpecFlow(name string) (polSpec, bool) { + switch name { + case apimCChoose: + return polSpec{kids: []string{apimCWhen, apimCOtherwise}, sections: allSections()}, true + case apimCSetVariable: + return polSpec{ + attrs: []string{fieldName, fieldValue}, required: []string{fieldName, fieldValue}, sections: allSections(), + }, true + case apimCSendRequest: + return polSpec{ + attrs: []string{apimCMode, apimCRespVar, apimCTimeout, "ignore-error"}, + required: []string{apimCRespVar}, + kids: []string{apimCSetURL, apimCSetMethod, apimCSetHeader, apimCSetBody, apimCAuthCertificate}, + sections: allSections(), + }, true + case apimCSendOneWay: + return polSpec{ + attrs: []string{apimCMode, apimCTimeout}, + kids: []string{apimCSetURL, apimCSetMethod, apimCSetHeader, apimCSetBody}, sections: allSections(), + }, true + case apimCRateLimitByKey: + return polSpec{ + attrs: []string{ + apimCCalls, apimCRenewalPeriod, apimCIncCondition, apimCIncCount, apimCCounterKey, + "retry-after-header-name", "retry-after-variable-name", "remaining-calls-header-name", + "remaining-calls-variable-name", "total-calls-header-name", + }, + required: []string{apimCCalls, apimCRenewalPeriod, apimCCounterKey}, + sections: []string{polInbound}, + }, true + case apimCQuota: + return polSpec{ + attrs: []string{apimCCalls, apimCBandwidth, apimCRenewalPeriod}, required: []string{apimCRenewalPeriod}, + kids: []string{apimCAPIElem}, sections: []string{polInbound}, + }, true + case apimCQuotaByKey: + return polSpec{ + attrs: []string{ + apimCCalls, apimCBandwidth, apimCRenewalPeriod, apimCIncCondition, apimCIncCount, apimCCounterKey, + apimCFirstPeriod, + }, + required: []string{apimCRenewalPeriod, apimCCounterKey}, sections: []string{polInbound}, + }, true + } + + return polSpec{}, false +} + +func extPolSpecCache(name string) (polSpec, bool) { + switch name { + case apimCCacheLookup: + return polSpec{ + attrs: []string{ + "vary-by-developer", "vary-by-developer-groups", apimCCachingType, apimCDownstream, "must-revalidate", + "allow-private-response-caching", + }, + kids: []string{apimCVaryHeader, apimCVaryQuery}, sections: []string{polInbound}, + }, true + case apimCCacheStore: + return polSpec{ + attrs: []string{apimCDuration, "cache-response"}, required: []string{apimCDuration}, + sections: []string{polOutbound}, + }, true + case apimCCacheLookupValue: + return polSpec{ + attrs: []string{apimCKey, apimCDefaultValue, apimCVariableName, apimCCachingType}, + required: []string{apimCKey, apimCVariableName}, sections: allSections(), + }, true + case apimCCacheStoreValue: + return polSpec{ + attrs: []string{apimCKey, fieldValue, apimCDuration, apimCCachingType}, + required: []string{apimCKey, fieldValue, apimCDuration}, sections: allSections(), + }, true + case apimCCacheRemoveValue: + return polSpec{ + attrs: []string{apimCKey, apimCCachingType}, required: []string{apimCKey}, sections: allSections(), + }, true + case apimCValidateJWT: + return polSpec{ + attrs: []string{ + "header-name", "query-parameter-name", "token-value", "failed-validation-httpcode", + "failed-validation-error-message", "require-expiration-time", "require-scheme", "require-signed-tokens", + "clock-skew", "output-token-variable-name", + }, + kids: []string{apimCOpenIDConfig, apimCSigningKeys, apimCAudiences, apimCIssuers, apimCRequiredClaims}, + sections: []string{polInbound}, + }, true + case apimCIncludeFragment: + return polSpec{attrs: []string{"fragment-id"}, required: []string{"fragment-id"}, sections: allSections()}, true + case apimCAuthCertificate: + return polSpec{ + attrs: []string{apimCThumbprint, apimCCertID, apimCBodyAttr, apimCPasswordAttr}, + sections: []string{polInbound}, + }, true + case apimCAuthBasic: + return polSpec{ + attrs: []string{apimCUsername, apimCPasswordAttr}, required: []string{apimCUsername, apimCPasswordAttr}, + sections: []string{polInbound}, + }, true + } + + return polSpec{}, false +} + +func extNestedSpec(name string) (polSpec, bool) { + switch name { + case apimCAuthCertificate: + return polSpec{attrs: []string{apimCThumbprint, apimCCertID, apimCBodyAttr, apimCPasswordAttr}}, true + case apimCSetURL, apimCSetMethod, apimCVaryHeader, apimCVaryQuery, apimCAudience, apimCIssuer: + return polSpec{}, true + case apimCWhen: + return polSpec{attrs: []string{apimCCondition}, required: []string{apimCCondition}}, true + case apimCOtherwise: + return polSpec{}, true + case apimCAPIElem: + return polSpec{ + attrs: []string{fieldName, apimCID, apimCCalls, apimCBandwidth, apimCRenewalPeriod}, + required: []string{apimCRenewalPeriod}, kids: []string{apimCOperationElem}, + }, true + case apimCOperationElem: + return polSpec{ + attrs: []string{ + fieldName, + apimCID, + apimCCalls, + apimCBandwidth, + apimCRenewalPeriod, + }, required: []string{apimCRenewalPeriod}, + }, true + case apimCOpenIDConfig: + return polSpec{attrs: []string{apimCUrl, "validate-connectivity"}, required: []string{apimCUrl}}, true + case apimCSigningKeys: + return polSpec{kids: []string{apimCKey}}, true + case apimCKey: + return polSpec{attrs: []string{apimCID, "n", "e", apimCCertID}}, true + case apimCAudiences: + return polSpec{kids: []string{apimCAudience}}, true + case apimCIssuers: + return polSpec{kids: []string{apimCIssuer}}, true + case apimCRequiredClaims: + return polSpec{kids: []string{"claim"}}, true + case "claim": + return polSpec{ + attrs: []string{fieldName, "match", "separator"}, required: []string{fieldName}, kids: []string{fieldValue}, + }, true + } + + return polSpec{}, false +} + +func intOrExpr(n *polNode, attr string, lo, hi int) error { + if v, has := n.Attrs[attr]; has { + if _, ok, _ := apimIsExprText(v); ok { + return nil + } + } + + return posInt(n, attr, lo, hi) +} + +func boolOrExpr(n *polNode, attr string) error { + v, has := n.Attrs[attr] + if !has { + return nil + } + + if _, ok, _ := apimIsExprText(v); ok || v == cmpTrue || v == apimCFalse { + return nil + } + + return polErr(n, "The attribute '%s' must be true, false or an expression.", attr) +} + +func oneOfOrExpr(n *polNode, attr string, allowed ...string) error { + v, has := n.Attrs[attr] + if !has { + return nil + } + + if _, ok, _ := apimIsExprText(v); ok || slices.Contains(allowed, v) { + return nil + } + + return polErr(n, "The attribute '%s' must be one of %s.", attr, strings.Join(allowed, ", ")) +} + +func validateExt(s *apimService, n *polNode) error { + switch n.Name { + case apimCIncludeFragment: + if s.Generic[apimFragmentsType][entKey("", n.Attrs["fragment-id"])] == nil { + return polErr(n, "The policy fragment '%s' does not exist.", n.Attrs["fragment-id"]) + } + case apimCRateLimitByKey: + return validateRateLimitByKey(n) + case apimCQuota, apimCQuotaByKey: + return validateQuota(n) + case apimCSetVariable: + if v := n.Attrs[fieldName]; v == "" || len(v) > apimMaxVariableName { + return polErr(n, "The variable name must be 1 to %d characters.", apimMaxVariableName) + } + case apimCAuthCertificate: + return validateAuthCert(s, n) + case apimCSendRequest, apimCSendOneWay: + if ac := n.kid(apimCAuthCertificate); ac != nil { + if err := validateAuthCert(s, ac); err != nil { + return err + } + } + + return validateSend(n) + case apimCValidateJWT: + return validateJWTPolicy(s, n) + default: + return validateExtCache(n) + } + + return nil +} + +func validateExtCache(n *polNode) error { + switch n.Name { + case apimCCacheLookup: + return validateCacheLookup(n) + case apimCCacheStore: + if err := boolOrExpr(n, "cache-response"); err != nil { + return err + } + + return intOrExpr(n, apimCDuration, 0, math.MaxInt32) + case apimCCacheLookupValue, apimCCacheStoreValue, apimCCacheRemoveValue: + if err := oneOfOrExpr(n, apimCCachingType, "internal", apimCExternal, "prefer-external"); err != nil { + return err + } + + return intOrExpr(n, apimCDuration, 1, math.MaxInt32) + } + + return nil +} + +func validateRateLimitByKey(n *polNode) error { + if err := intOrExpr(n, apimCCalls, 1, math.MaxInt32); err != nil { + return err + } + + if err := intOrExpr(n, apimCRenewalPeriod, 1, apimMaxRenewalSecs); err != nil { + return err + } + + return intOrExpr(n, apimCIncCount, 1, math.MaxInt32) +} + +func validateQuota(n *polNode) error { + if n.Name == apimCQuota && !strings.HasPrefix(strings.TrimPrefix(n.Scope, "svc|"), "products/") { + return polErr(n, "The quota policy can be used at the product scope only.") + } + + for _, e := range append([]*polNode{n}, n.Kids...) { + if err := validateQuotaElement(e); err != nil { + return err + } + + for _, o := range e.Kids { + if err := validateQuotaElement(o); err != nil { + return err + } + } + } + + if n.Name == apimCQuotaByKey { + if err := intOrExpr(n, apimCIncCount, 1, math.MaxInt32); err != nil { + return err + } + + if v := n.Attrs[apimCRenewalPeriod]; v != "0" { + if err := posInt(n, apimCRenewalPeriod, apimMinKeyedRenewal, math.MaxInt32); err != nil { + return err + } + } + } + + return nil +} + +func validateQuotaElement(e *polNode) error { + if e.Name == apimCAPIElem || e.Name == apimCOperationElem { + if e.Attrs[apimCID] == "" && e.Attrs[fieldName] == "" { + return polErr(e, "Either 'name' or 'id' is required.") + } + } + + _, hasCalls := e.Attrs[apimCCalls] + _, hasBW := e.Attrs[apimCBandwidth] + + if !hasCalls && !hasBW { + return polErr(e, "Either 'calls' or 'bandwidth' must be specified.") + } + + if err := posInt(e, apimCCalls, 1, math.MaxInt32); err != nil { + return err + } + + if err := posInt(e, apimCBandwidth, 1, math.MaxInt32); err != nil { + return err + } + + return posInt(e, apimCRenewalPeriod, 0, math.MaxInt32) +} + +func validateCacheLookup(n *polNode) error { + bools := []string{ + "vary-by-developer", + "vary-by-developer-groups", + "must-revalidate", + "allow-private-response-caching", + } + + for _, b := range bools { + if err := boolOrExpr(n, b); err != nil { + return err + } + } + + if v := n.Attrs[apimCCachingType]; v != "" && + !slices.Contains([]string{"internal", apimCExternal, "prefer-external"}, v) { + return polErr(n, "The attribute 'caching-type' must be internal, external or prefer-external.") + } + + return oneOfOrExpr(n, apimCDownstream, "none", "private", "public") +} + +func validateSend(n *polNode) error { + if err := oneOfOrExpr(n, apimCMode, "new", apimModeCopy); err != nil { + return err + } + + if v := n.Attrs["ignore-error"]; v != "" && v != cmpTrue && v != apimCFalse { + return polErr(n, "The attribute 'ignore-error' must be true or false.") + } + + if err := intOrExpr(n, apimCTimeout, 1, int(apimForwardTimeout.Seconds())); err != nil { + return err + } + + if n.Attrs[apimCMode] == apimModeCopy { + return nil + } + + for _, k := range []string{apimCSetURL, apimCSetMethod} { + if n.kid(k) == nil || strings.TrimSpace(n.kid(k).Text) == "" { + return polErr(n, "The <%s> element is required unless mode is copy.", k) + } + } + + if u := strings.TrimSpace(n.kid(apimCSetURL).Text); !strings.Contains(u, "@") && !strings.Contains(u, "{{") && + !validAbsURL(u, acaScaleHTTP, acaSchemeHTTPS) { + return polErr(n.kid(apimCSetURL), "The set-url must be an absolute http or https URL.") + } + + if m := strings.TrimSpace(n.kid(apimCSetMethod).Text); !strings.Contains(m, "@") && + !apimSendMethodOK(strings.ToUpper(m)) { + return polErr(n.kid(apimCSetMethod), "The set-method must be GET, POST, PUT, PATCH, DELETE, HEAD or OPTIONS.") + } + + return nil +} + +func validateJWTPolicy(s *apimService, n *polNode) error { + sources := 0 + + for _, a := range []string{"header-name", "query-parameter-name", "token-value"} { + if n.Attrs[a] != "" { + sources++ + } + } + + if sources != 1 { + return polErr(n, "Exactly one of header-name, query-parameter-name and token-value is required.") + } + + if err := intOrExpr(n, "failed-validation-httpcode", apimMinStatus, apimMaxStatus); err != nil { + return err + } + + if err := intOrExpr(n, "clock-skew", 0, apimJWTMaxClockSkew); err != nil { + return err + } + + for _, b := range []string{"require-expiration-time", "require-signed-tokens"} { + if err := boolOrExpr(n, b); err != nil { + return err + } + } + + if n.kid(apimCOpenIDConfig) == nil && n.kid(apimCSigningKeys) == nil && + n.Attrs["require-signed-tokens"] != apimCFalse { + return polErr(n, "An openid-config or issuer-signing-keys element is required to validate signed tokens.") + } + + return validateJWTElements(s, n) +} + +func validateJWTElements(s *apimService, n *polNode) error { + for _, oc := range n.Kids { + if oc.Name != apimCOpenIDConfig { + continue + } + + u := oc.Attrs[apimCUrl] + if !strings.Contains(u, "@") && !strings.Contains(u, "{{") && !validAbsURL(u, acaScaleHTTP, acaSchemeHTTPS) { + return polErr(oc, "The openid-config url must be an absolute http or https URL.") + } + } + + if sk := n.kid(apimCSigningKeys); sk != nil { + for _, k := range sk.Kids { + if err := validateSigningKey(s, k); err != nil { + return err + } + } + } + + if rc := n.kid(apimCRequiredClaims); rc != nil { + for _, c := range rc.Kids { + if m := c.Attrs["match"]; m != "" && m != "all" && m != apimMatchAny { + return polErr(c, "The attribute 'match' must be all or any.") + } + } + } + + return nil +} + +func validateSigningKey(s *apimService, k *polNode) error { + _, hasN := k.Attrs["n"] + _, hasE := k.Attrs["e"] + + if id := k.Attrs[apimCCertID]; id != "" { + if s.Generic[apimCertificatesType][entKey("", id)] == nil { + return polErr(k, "The certificate '%s' does not exist.", id) + } + + return nil + } + + if hasN != hasE { + return polErr(k, "The attributes 'n' and 'e' must be given together.") + } + + if hasN { + if _, ok := apimRSAKey(k.Attrs["n"], k.Attrs["e"]); !ok { + return polErr(k, "The modulus and exponent must be Base64url-encoded RSA public key parts.") + } + + return nil + } + + txt := strings.TrimSpace(k.Text) + if txt == "" { + return polErr(k, "The key needs Base64 text or the n and e attributes.") + } + + if strings.Contains(txt, "{{") || strings.Contains(txt, "@") { + return nil + } + + if b, err := base64.StdEncoding.DecodeString(txt); err != nil || len(b) == 0 { + return polErr(k, "The key is not valid Base64.") + } + + return nil +} + +// validateFragment checks that a policy fragment is a of supported statements without nested includes. +func validateFragment(s *apimService, doc string) error { + root, err := parsePolicy(doc, "svc|fragment") + if err != nil { + return err + } + + if root.Name != "fragment" { + return polErr(root, "The root element of a policy fragment must be .") + } + + for _, st := range root.Kids { + if st.Name == apimCIncludeFragment || st.Name == polBase { + return polErr(st, "The element is not allowed in a policy fragment.") + } + + if err = validateStatement(s, st, apimSectionAny); err != nil { + return err + } + } + + return nil +} + +func (s *apimService) fragmentMap() map[string]string { + out := make(map[string]string, len(s.Generic[apimFragmentsType])) + for _, e := range s.Generic[apimFragmentsType] { + out[strings.ToLower(e.ID)] = strOf(e.Props, fieldValue) + } + + return out +} + +var errAPIMFragment = errors.New("policy fragment not found") + +// inlineFragments replaces include-fragment statements by the statements of the fragment, one level deep. +func (g *gwState) inlineFragments(n *polNode) error { + var kids []*polNode + + for _, k := range n.Kids { + if k.Name != apimCIncludeFragment { + if err := g.inlineFragments(k); err != nil { + return err + } + + kids = append(kids, k) + + continue + } + + doc, ok := g.plan.fragments[strings.ToLower(k.Attrs["fragment-id"])] + if !ok { + return errAPIMFragment + } + + root, err := parsePolicy(doc, k.Scope) + if err != nil { + return err + } + + for _, c := range root.Kids { + retag(c, k) + kids = append(kids, c) + } + } + + n.Kids = kids + + return nil +} + +func retag(n, inc *polNode) { + n.Scope, n.Line = inc.Scope, inc.Line< apimMaxSendBody { + g.evalErr = apimExprFail("the request body is too large") + + return nil, false + } + + req, err := http.NewRequestWithContext(ctx, method, target, bytes.NewReader(body)) + if err != nil { + g.evalErr = apimExprFail("the request could not be built") + + return nil, false + } + + copyForwardHeaders(req.Header, hdr) + + return req, true +} + +func (g *gwState) sendTimeout(n *polNode) time.Duration { + secs := g.intAttr(n, apimCTimeout, apimSendTimeoutSecs) + if secs < 1 || secs > int64(apimForwardTimeout/time.Second) { + g.evalErr = apimExprFail("the timeout must be 1 to %d seconds", int64(apimForwardTimeout/time.Second)) + } + + return time.Duration(secs) * time.Second +} + +func (g *gwState) sendRequest(n *polNode) { + if n.Name == apimCSendOneWay { + g.sendOneWay(n) + + return + } + + timeout := g.sendTimeout(n) + if g.evalErr != nil { + return + } + + ctx, cancel := context.WithTimeout(g.r.Context(), timeout) + defer cancel() + + req, ok := g.buildSend(ctx, n) + if !ok { + return + } + + name := g.sub(n.Attrs[apimCRespVar]) + ignore := n.Attrs["ignore-error"] == cmpTrue + + client := g.sendClient(n) + if g.errored { + return + } + + resp, err := client.Do(req) + if err != nil { + if ignore { + g.vars[name] = nil + + return + } + + g.upstreamError(err) + + return + } + + defer resp.Body.Close() + + body, err := io.ReadAll(io.LimitReader(resp.Body, apimMaxCacheEntry+1)) + if err != nil || len(body) > apimMaxCacheEntry { + if ignore { + g.vars[name] = nil + + return + } + + g.failR(http.StatusBadGateway, "BackendConnectionFailure", "The send-request response could not be read.") + + return + } + + g.vars[name] = &apimExprResponse{status: resp.StatusCode, header: resp.Header.Clone(), body: body} +} + +func (g *gwState) sendOneWay(n *polNode) { + timeout := g.sendTimeout(n) + if g.evalErr != nil { + return + } + + ctx, cancel := context.WithTimeout(context.WithoutCancel(g.r.Context()), timeout) + + req, ok := g.buildSend(ctx, n) + if !ok { + cancel() + + return + } + + client := g.sendClient(n) + if g.errored { + cancel() + + return + } + + select { + case g.p.oneWay <- struct{}{}: + default: + cancel() + g.failR(http.StatusServiceUnavailable, "BackendConnectionFailure", "Too many one-way requests are in flight.") + + return + } + + id, ok := g.p.bg.begin(cancel) + if !ok { + <-g.p.oneWay + cancel() + g.failR(http.StatusServiceUnavailable, "BackendConnectionFailure", "The gateway is shutting down.") + + return + } + + go func() { + defer g.p.bg.end(id) + defer func() { <-g.p.oneWay }() + defer cancel() + + resp, err := client.Do(req) + if err != nil { + return + } + + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, apimMaxCacheEntry)) + _ = resp.Body.Close() + }() +} + +func (g *gwState) authBasic(n *polNode) { + cred := g.sub(n.Attrs["username"]) + ":" + g.sub(n.Attrs["password"]) + g.basicAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(cred)) +} diff --git a/services/azurearm/rp_apim_state.go b/services/azurearm/rp_apim_state.go new file mode 100644 index 0000000000..4f4334856b --- /dev/null +++ b/services/azurearm/rp_apim_state.go @@ -0,0 +1,260 @@ +package azurearm + +import ( + "net/http" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" +) + +const ( + apimMaxQuotaEntries = 100000 + apimMaxCacheEntries = 10000 + apimMaxCacheBytes = 64 << 20 + apimMaxCacheEntry = 1 << 20 + apimMaxCounterKey = 2048 + apimMaxOneWay = 64 +) + +func apimNewGUID() string { return uuid.NewString() } + +// apimKeyOf length-prefixes each part so that parts containing the separator cannot collide. +func apimKeyOf(parts ...string) string { + var sb strings.Builder + + for _, p := range parts { + sb.WriteString(strconv.Itoa(len(p))) + sb.WriteByte(':') + sb.WriteString(p) + } + + return sb.String() +} + +type apimQuotaEntry struct { + start, end time.Time + calls, bytes int64 +} + +// apimQuotaStore holds quota counters in memory; like the built-in cache it is volatile. +type apimQuotaStore struct { + mu *lockmetrics.RWMutex + m map[string]*apimQuotaEntry +} + +func newAPIMQuotaStore() *apimQuotaStore { + return &apimQuotaStore{mu: lockmetrics.New("azurearm.apim.quota"), m: map[string]*apimQuotaEntry{}} +} + +func (q *apimQuotaStore) reset() { + q.mu.Lock("reset") + q.m = map[string]*apimQuotaEntry{} + q.mu.Unlock() +} + +// quotaWindow is the fixed window containing now; windows start at first and repeat every period (0: one window). +func quotaWindow(now, first time.Time, period time.Duration) (time.Time, time.Time) { + if period <= 0 { + return first, time.Time{} + } + + secs := int64(period / time.Second) + delta := now.Unix() - first.Unix() + + if delta < 0 { + return first, first.Add(period) + } + + start := first.Add(time.Duration(delta/secs*secs) * time.Second) + + return start, start.Add(period) +} + +func (q *apimQuotaStore) entry(key string, now, first time.Time, period time.Duration) *apimQuotaEntry { + start, end := quotaWindow(now, first, period) + + e := q.m[key] + if e == nil || !e.start.Equal(start) { + if len(q.m) >= apimMaxQuotaEntries/2 { + for k, o := range q.m { + if !o.end.IsZero() && !now.Before(o.end) { + delete(q.m, k) + } + } + } + + for len(q.m) >= apimMaxQuotaEntries { + for k := range q.m { + delete(q.m, k) + + break + } + } + + e = &apimQuotaEntry{start: start, end: end} + q.m[key] = e + } + + return e +} + +// quotaReq is one counter an admission checks and, when every counter has room, charges. +type quotaReq struct { + first time.Time + key string + period time.Duration + calls, kb int64 + chargeCalls int64 +} + +// admit checks every counter and, only when all have room, charges their calls, in one critical section so that +// concurrent requests cannot all pass the same check. +func (q *apimQuotaStore) admit(now time.Time, reqs []quotaReq) (string, time.Duration) { + q.mu.Lock("admit") + defer q.mu.Unlock() + + entries := make([]*apimQuotaEntry, len(reqs)) + + for i, r := range reqs { + e := q.entry(r.key, now, r.first, r.period) + entries[i] = e + + var retry time.Duration + if !e.end.IsZero() { + retry = e.end.Sub(now) + } + + switch { + case r.calls > 0 && e.calls >= r.calls: + return "calls", retry + case r.kb > 0 && e.bytes >= r.kb*1024: + return "bandwidth", retry + } + } + + for i, r := range reqs { + entries[i].calls += r.chargeCalls + } + + return "", 0 +} + +func (q *apimQuotaStore) add(key string, now, first time.Time, period time.Duration, calls, bytes int64) { + q.mu.Lock("add") + defer q.mu.Unlock() + + e := q.entry(key, now, first, period) + e.calls += calls + e.bytes += bytes +} + +type apimCacheEntry struct { + expires time.Time + value any + size int +} + +type gwCachedResponse struct { + header http.Header + body []byte + status int +} + +// apimCache is the volatile per-service response and value cache. +type apimCache struct { + mu *lockmetrics.RWMutex + m map[string]*apimCacheEntry + bytes int +} + +func newAPIMCache() *apimCache { + return &apimCache{mu: lockmetrics.New("azurearm.apim.cache"), m: map[string]*apimCacheEntry{}} +} + +func (c *apimCache) reset() { + c.mu.Lock("reset") + c.m, c.bytes = map[string]*apimCacheEntry{}, 0 + c.mu.Unlock() +} + +func (c *apimCache) get(key string, now time.Time) (any, time.Time, bool) { + c.mu.Lock("lookup") + defer c.mu.Unlock() + + e := c.m[key] + if e == nil { + return nil, time.Time{}, false + } + + if !now.Before(e.expires) { + c.drop(key) + + return nil, time.Time{}, false + } + + return e.value, e.expires, true +} + +func (c *apimCache) drop(key string) { + if e := c.m[key]; e != nil { + c.bytes -= e.size + delete(c.m, key) + } +} + +func (c *apimCache) remove(key string) { + c.mu.Lock("remove") + c.drop(key) + c.mu.Unlock() +} + +// put stores a value unless it exceeds the per-entry bound. +func (c *apimCache) put(key string, v any, size int, ttl time.Duration, now time.Time) { + if size > apimMaxCacheEntry || ttl <= 0 { + return + } + + c.mu.Lock("put") + defer c.mu.Unlock() + + c.drop(key) + c.evict(now, size) + + c.m[key] = &apimCacheEntry{value: v, size: size, expires: now.Add(ttl)} + c.bytes += size +} + +func (c *apimCache) evict(now time.Time, incoming int) { + if len(c.m) < apimMaxCacheEntries && c.bytes+incoming <= apimMaxCacheBytes { + return + } + + for k, e := range c.m { + if !now.Before(e.expires) { + c.drop(k) + } + } + + for len(c.m) >= apimMaxCacheEntries || c.bytes+incoming > apimMaxCacheBytes { + var ( + oldest string + at time.Time + ) + + for k, e := range c.m { + if oldest == "" || e.expires.Before(at) { + oldest, at = k, e.expires + } + } + + if oldest == "" { + return + } + + c.drop(oldest) + } +} diff --git a/services/azurearm/rp_apim_throttle.go b/services/azurearm/rp_apim_throttle.go new file mode 100644 index 0000000000..65002d95b3 --- /dev/null +++ b/services/azurearm/rp_apim_throttle.go @@ -0,0 +1,318 @@ +package azurearm + +import ( + "fmt" + "math" + "net/http" + "strconv" + "strings" + "time" +) + +const ( + apimCRateLimitByKey = "rate-limit-by-key" + apimCQuota = "quota" + apimCQuotaByKey = "quota-by-key" + apimCCounterKey = "counter-key" + apimCIncCondition = "increment-condition" + apimCIncCount = "increment-count" + apimCBandwidth = "bandwidth" + apimCFirstPeriod = "first-period-start" + apimMinKeyedRenewal = 300 + apimQuotaTimeFmt = "2006-01-02T15:04:05Z" + apimSecsPerDay = 86400 + apimSecsPerHour = 3600 + apimSecsPerMin = 60 +) + +func apimQuotaMessage(kind string, left time.Duration) string { + what := "call volume" + if kind == apimCBandwidth { + what = "bandwidth" + } + + msg := "Out of " + what + " quota." + if left <= 0 { + return msg + } + + secs := int64(math.Ceil(left.Seconds())) + d, rest := secs/apimSecsPerDay, secs%apimSecsPerDay + h, m, s := rest/apimSecsPerHour, rest%apimSecsPerHour/apimSecsPerMin, rest%apimSecsPerMin + + if d > 0 { + return fmt.Sprintf("%s Quota will be replenished in %d.%02d:%02d:%02d.", msg, d, h, m, s) + } + + return fmt.Sprintf("%s Quota will be replenished in %02d:%02d:%02d.", msg, h, m, s) +} + +func apimIsExprAttr(n *polNode, attr string) bool { + _, ok, _ := apimIsExprText(n.Attrs[attr]) + + return ok +} + +func (g *gwState) keyAttr(n *polNode) (string, bool) { + key := g.sub(n.Attrs[apimCCounterKey]) + if g.evalErr != nil { + return "", false + } + + if len(key) > apimMaxCounterKey { + g.evalErr = apimExprFail("the counter-key is longer than %d characters", apimMaxCounterKey) + + return "", false + } + + return key, true +} + +func (g *gwState) rateLimitByKey(n *polNode) { + calls, period := g.intAttr(n, apimCCalls, 0), g.intAttr(n, apimCRenewalPeriod, 0) + + key, ok := g.keyAttr(n) + if !ok { + return + } + + if calls < 1 || calls > math.MaxInt32 || period < 1 || period > apimMaxRenewalSecs { + g.evalErr = apimExprFail("calls must be 1 to %d and renewal-period 1 to %d", math.MaxInt32, apimMaxRenewalSecs) + + return + } + + full, per := apimKeyOf(g.plan.svcKey, "rlbk", key), time.Duration(period)*time.Second + allowed, left, retry := g.rateCheck(n, full, calls, per) + + g.rateHeaders(n, calls, left) + + if allowed { + return + } + + secs := strconv.Itoa(int(math.Ceil(retry.Seconds()))) + + g.failR(http.StatusTooManyRequests, "RateLimitExceeded", apimMsgRateLimit) + g.respHeader.Set(firstNonEmpty(n.Attrs["retry-after-header-name"], apimCRetryAfter), secs) + + if v := n.Attrs["retry-after-variable-name"]; v != "" { + g.vars[v] = int64(math.Ceil(retry.Seconds())) + } +} + +// rateCheck counts the call now, or only checks it and counts at the end of the pipeline when the increment +// depends on the response. +func (g *gwState) rateCheck(n *polNode, key string, calls int64, per time.Duration) (bool, int, time.Duration) { + switch { + case apimIsExprAttr(n, apimCIncCondition) || apimIsExprAttr(n, apimCIncCount): + allowed, left, retry := g.p.limiter.peek(key, int(calls), per, g.now()) + + g.deferred = append(g.deferred, func(int64) { + cond, cnt := g.boolAttr(n, apimCIncCondition, true), g.intAttr(n, apimCIncCount, 1) + if cond && cnt > 0 && cnt <= calls && g.evalErr == nil { + g.p.limiter.add(key, int(cnt), per, g.now()) + } + + g.evalErr = nil + }) + + return allowed, left, retry + case g.boolAttr(n, apimCIncCondition, true): + cnt := min(g.intAttr(n, apimCIncCount, 1), calls) + + return g.p.limiter.take(key, int(calls), int(max(cnt, 1)), per, g.now()) + } + + return g.p.limiter.peek(key, int(calls), per, g.now()) +} + +func (g *gwState) rateHeaders(n *polNode, calls int64, left int) { + if h := n.Attrs["total-calls-header-name"]; h != "" { + g.extra.Set(h, strconv.FormatInt(calls, 10)) + } + + if h := n.Attrs["remaining-calls-header-name"]; h != "" { + g.extra.Set(h, strconv.Itoa(left)) + } + + if v := n.Attrs["remaining-calls-variable-name"]; v != "" { + g.vars[v] = int64(left) + } +} + +func (g *gwState) quotaDeny(kind string, retry time.Duration) { + g.failR(http.StatusForbidden, "QuotaExceeded", apimQuotaMessage(kind, retry)) + + if retry > 0 { + g.respHeader.Set(apimCRetryAfter, strconv.Itoa(int(math.Ceil(retry.Seconds())))) + } +} + +func (g *gwState) requestBytes() int64 { return max(g.r.ContentLength, 0) } + +type quotaArgs struct { + first time.Time + calls, kb, every int64 +} + +// quotaByKeyArgs reads and validates the numeric and date attributes of quota-by-key. +func (g *gwState) quotaByKeyArgs(n *polNode) (quotaArgs, bool) { + a := quotaArgs{ + calls: g.intAttr(n, apimCCalls, 0), kb: g.intAttr(n, apimCBandwidth, 0), + every: g.intAttr(n, apimCRenewalPeriod, 0), + } + + if v := n.Attrs[apimCFirstPeriod]; v != "" { + t, err := time.Parse(apimQuotaTimeFmt, v) + if err != nil { + g.evalErr = apimExprFail("first-period-start is not a yyyy-MM-ddTHH:mm:ssZ date") + + return a, false + } + + a.first = t + } + + if g.evalErr != nil || a.every < 0 || (a.every > 0 && a.every < apimMinKeyedRenewal) || a.calls < 0 || a.kb < 0 { + g.evalErr = apimExprFail("renewal-period must be 0 or at least %d seconds", apimMinKeyedRenewal) + + return a, false + } + + return a, true +} + +func (g *gwState) quotaByKey(n *polNode) { + key, ok := g.keyAttr(n) + if !ok { + return + } + + args, ok := g.quotaByKeyArgs(n) + if !ok { + return + } + + calls, kb, first := args.calls, args.kb, args.first + + full, per := apimKeyOf(g.plan.svcKey, "qbk", key), time.Duration(args.every)*time.Second + + charge, static := g.quotaCharge(n, full) + if g.evalErr != nil { + return + } + + req := quotaReq{key: full, first: first, period: per, calls: calls, kb: kb, chargeCalls: charge} + if kind, retry := g.p.quotas.admit(g.now(), []quotaReq{req}); kind != "" { + g.quotaDeny(kind, retry) + + return + } + + if static { + if charge > 0 { + g.deferred = append(g.deferred, func(written int64) { + g.p.quotas.add(full, g.now(), first, per, 0, written+g.requestBytes()) + }) + } + + return + } + + g.deferred = append(g.deferred, func(written int64) { + cond, cnt := g.boolAttr(n, apimCIncCondition, true), g.intAttr(n, apimCIncCount, 1) + + defer func() { g.evalErr = nil }() + + if !cond || cnt < 1 || g.evalErr != nil || g.seenKeys[full] { + return + } + + g.seenKeys[full] = true + g.p.quotas.add(full, g.now(), first, per, cnt, written+g.requestBytes()) + }) +} + +// quotaCharge is the calls to charge up front: the increment is known only after the response when its condition +// or count is an expression. +func (g *gwState) quotaCharge(n *polNode, full string) (int64, bool) { + if apimIsExprAttr(n, apimCIncCondition) || apimIsExprAttr(n, apimCIncCount) { + return 0, false + } + + cond, cnt := g.boolAttr(n, apimCIncCondition, true), g.intAttr(n, apimCIncCount, 1) + if !cond || cnt < 1 || g.seenKeys[full] { + return 0, true + } + + g.seenKeys[full] = true + + return cnt, true +} + +type gwQuotaScope struct { + n *polNode + key string +} + +func (g *gwState) quota(n *polNode) { + if g.plan.subID == "" { + return + } + + scopes := []gwQuotaScope{{n: n, key: apimScopeProduct}} + + for _, a := range n.Kids { + if a.Name != apimCAPIElem || !g.quotaTargets(a, g.plan.apiID, strOf(g.plan.api, apimCDisplayName)) { + continue + } + + scopes = append(scopes, gwQuotaScope{n: a, key: "api:" + a.Attrs[apimCID] + a.Attrs[fieldName]}) + + for _, o := range a.Kids { + if o.Name == apimCOperationElem && g.plan.opID != "" && + g.quotaTargets(o, g.plan.opID, strOf(g.plan.op, apimCDisplayName)) { + scopes = append( + scopes, + gwQuotaScope{n: o, key: "op:" + g.plan.apiID + "/" + o.Attrs[apimCID] + o.Attrs[fieldName]}, + ) + } + } + } + + reqs := make([]quotaReq, 0, len(scopes)) + + for _, sc := range scopes { + reqs = append(reqs, quotaReq{ + key: apimKeyOf(g.plan.svcKey, "quota", g.plan.subID, sc.key), + first: g.plan.subStart, + period: time.Duration(g.intAttr(sc.n, apimCRenewalPeriod, 0)) * time.Second, + calls: g.intAttr(sc.n, apimCCalls, 0), kb: g.intAttr(sc.n, apimCBandwidth, 0), chargeCalls: 1, + }) + } + + if g.evalErr != nil { + return + } + + if kind, retry := g.p.quotas.admit(g.now(), reqs); kind != "" { + g.quotaDeny(kind, retry) + + return + } + + g.deferred = append(g.deferred, func(written int64) { + for _, r := range reqs { + g.p.quotas.add(r.key, g.now(), r.first, r.period, 0, written+g.requestBytes()) + } + }) +} + +func (g *gwState) quotaTargets(e *polNode, id, name string) bool { + if v := e.Attrs[apimCID]; v != "" { + return strings.EqualFold(v, id) + } + + return e.Attrs[fieldName] != "" && strings.EqualFold(e.Attrs[fieldName], name) +} diff --git a/services/azurearm/rp_apim_ws.go b/services/azurearm/rp_apim_ws.go new file mode 100644 index 0000000000..c0dc624c2f --- /dev/null +++ b/services/azurearm/rp_apim_ws.go @@ -0,0 +1,128 @@ +package azurearm + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httputil" + "net/url" + "strings" + "time" +) + +const ( + apimWSMaxSessions = 256 + apimWSMaxLifetime = time.Hour + apimSchemeWS = "ws" + apimSchemeWSS = "wss" +) + +var errAPIMNotUpgrade = errors.New("the API is a WebSocket API and the request is not a WebSocket upgrade") + +func apimIsWebSocket(r *http.Request) bool { + return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") && + strings.Contains(strings.ToLower(r.Header.Get("Connection")), "upgrade") +} + +func apimWSScheme(tls bool) string { + if tls { + return apimSchemeWSS + } + + return apimSchemeWS +} + +// apimHTTPScheme maps the ws and wss schemes of a WebSocket serviceUrl to the scheme used to dial the backend. +func apimHTTPScheme(s string) string { + switch s { + case apimSchemeWS: + return acaScaleHTTP + case apimSchemeWSS: + return acaSchemeHTTPS + } + + return s +} + +// wsTransport closes an upgraded connection after its maximum lifetime. +type wsTransport struct { + base http.RoundTripper + max time.Duration +} + +func (t wsTransport) RoundTrip(req *http.Request) (*http.Response, error) { + resp, err := t.base.RoundTrip(req) + if err != nil || resp.StatusCode != http.StatusSwitchingProtocols { + return resp, err + } + + if rwc, ok := resp.Body.(io.ReadWriteCloser); ok { + resp.Body = &wsConn{ReadWriteCloser: rwc, timer: time.AfterFunc(t.max, func() { _ = rwc.Close() })} + } + + return resp, nil +} + +type wsConn struct { + io.ReadWriteCloser + + timer *time.Timer +} + +func (c *wsConn) Close() error { + c.timer.Stop() + + return c.ReadWriteCloser.Close() +} + +// proxyWebSocket passes a WebSocket handshake, with the policies already applied to it, to the backend and then +// copies frames both ways until either side closes. +func (g *gwState) proxyWebSocket(u *url.URL) { + select { + case g.p.wsSlots <- struct{}{}: + defer func() { <-g.p.wsSlots }() + default: + g.failR(http.StatusServiceUnavailable, "BackendConnectionFailure", "Too many WebSocket connections are open.") + + return + } + + ctx, cancel := context.WithCancel(g.r.Context()) + + id, ok := g.p.bg.begin(cancel) + if !ok { + cancel() + g.failR(http.StatusServiceUnavailable, "BackendConnectionFailure", "The gateway is shutting down.") + + return + } + + defer g.p.bg.end(id) + defer cancel() + + rp := &httputil.ReverseProxy{ + Transport: wsTransport{base: g.httpClient().Transport, max: apimWSMaxLifetime}, + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL = u + pr.Out.Host = u.Host + pr.Out.Header = http.Header{} + copyForwardHeaders(pr.Out.Header, g.header) + pr.Out.Header.Set(apimHeaderXForward, hostOnly(g.r.RemoteAddr)) + pr.Out.Header.Set("Upgrade", "websocket") + pr.Out.Header.Set("Connection", "Upgrade") + g.applyCredentials(pr.Out) + + if g.basicAuth != "" { + pr.Out.Header.Set(apimCAuthorizationX, g.basicAuth) + } + }, + ErrorHandler: func(_ http.ResponseWriter, _ *http.Request, err error) { g.upstreamError(err) }, + } + + rp.ServeHTTP(g.w, g.r.WithContext(ctx)) + + if !g.errored { + g.wrote = true + } +} diff --git a/services/azurearm/rp_logic.go b/services/azurearm/rp_logic.go index 24416f26c0..7a6f1246c4 100644 --- a/services/azurearm/rp_logic.go +++ b/services/azurearm/rp_logic.go @@ -3,6 +3,7 @@ package azurearm import ( "context" "crypto/rand" + "crypto/x509" "encoding/base64" "encoding/hex" "fmt" @@ -61,12 +62,16 @@ type logicVersion struct { } type logicTriggerState struct { - Anchor time.Time `json:"anchor"` - Created time.Time `json:"created"` - Changed time.Time `json:"changed"` - Last *time.Time `json:"last,omitempty"` - Next *time.Time `json:"next,omitempty"` - State string `json:"state"` + Anchor time.Time `json:"anchor"` + Created time.Time `json:"created"` + Changed time.Time `json:"changed"` + Last *time.Time `json:"last,omitempty"` + Next *time.Time `json:"next,omitempty"` + PollURL string `json:"pollUrl,omitempty"` + Hook *logicHookRec `json:"hook,omitempty"` + State string `json:"state"` + + HookPending bool `json:"-"` } type logicContent struct { @@ -91,17 +96,19 @@ type logicRunTrigger struct { } type logicActionRec struct { - Start time.Time `json:"start"` - End time.Time `json:"end"` - Error any `json:"error,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Status string `json:"status"` - Code string `json:"code,omitempty"` - Tracking string `json:"tracking,omitempty"` - Inputs logicContent `json:"inputs"` - Outputs logicContent `json:"outputs"` - Taints bool `json:"taints,omitempty"` + End time.Time `json:"end"` + Start time.Time `json:"start"` + Error any `json:"error,omitempty"` + Inputs logicContent `json:"inputs"` + Outputs logicContent `json:"outputs"` + Name string `json:"name"` + Code string `json:"code,omitempty"` + Tracking string `json:"tracking,omitempty"` + Status string `json:"status"` + Type string `json:"type"` + Requests []*logicRequestRec `json:"requests,omitempty"` + Traces []*logicTraceRoot `json:"traces,omitempty"` + Taints bool `json:"taints,omitempty"` } type logicRepIndex struct { @@ -113,8 +120,8 @@ type logicRepIndex struct { type logicRepRec struct { Action string `json:"action"` Name string `json:"name"` - Rec logicActionRec `json:"rec"` Indexes []logicRepIndex `json:"indexes"` + Rec logicActionRec `json:"rec"` Scope bool `json:"scope,omitempty"` } @@ -172,23 +179,29 @@ type logicWorkflow struct { Versions []*logicVersion `json:"versions"` Runs []*logicRunRec `json:"runs"` Histories []*logicHistory `json:"histories"` + Operations []*logicOperation `json:"operations,omitempty"` } // LogicProvider implements ResourceProvider for Microsoft.Logic Consumption workflows: ARM CRUD, run history and // the workflow engine that executes definitions. type LogicProvider struct { - clock gcpscale.Clock - http *http.Client - mu *lockmetrics.RWMutex - wf map[string]*logicWorkflow - live map[string]*logicLive - queue map[string][]*logicQueued - timers map[string]gcpscale.Timer - rootCtx context.Context //nolint:containedctx // lifetime of every run goroutine - cancel context.CancelFunc - wg sync.WaitGroup - seq atomic.Int64 - external atomic.Bool + rootCtx context.Context //nolint:containedctx // lifetime of every run goroutine + clock gcpscale.Clock + cancel context.CancelFunc + roots atomic.Pointer[x509.CertPool] + live map[string]*logicLive + queue map[string][]*logicQueued + timers map[string]gcpscale.Timer + mu *lockmetrics.RWMutex + http atomic.Pointer[http.Client] + wf map[string]*logicWorkflow + hookBases map[string]string + hookQ []*logicHookJob + wg sync.WaitGroup + hookPort int + seq atomic.Int64 + external atomic.Bool + hookRun bool } // NewLogicProvider creates a LogicProvider on the wall clock. @@ -200,7 +213,7 @@ func NewLogicProvider() *LogicProvider { timers: map[string]gcpscale.Timer{}, rootCtx: ctx, cancel: cancel, } - p.http = p.newHTTPClient() + p.http.Store(p.newHTTPClient()) return p } @@ -240,6 +253,7 @@ func (p *LogicProvider) ResourceTypes() []ResourceTypeDef { {Type: logicWorkflowsType + "/triggers/histories", APIVersions: v}, {Type: logicWorkflowsType + "/runs", APIVersions: v}, {Type: logicWorkflowsType + "/runs/actions", APIVersions: v}, + {Type: logicWorkflowsType + "/runs/actions/requestHistories", APIVersions: v}, {Type: logicWorkflowsType + "/versions", APIVersions: v}, } } @@ -334,7 +348,6 @@ func (p *LogicProvider) workflowLocked(id ResourceID) (*logicWorkflow, error) { func (p *LogicProvider) Delete(_ context.Context, id ResourceID) error { p.mu.Lock("Delete") w, err := p.workflowLocked(id) - if err != nil { p.mu.Unlock() @@ -351,7 +364,10 @@ func (p *LogicProvider) Delete(_ context.Context, id ResourceID) error { // detachLocked removes w and returns its live runs for cancellation; caller holds p.mu. func (p *LogicProvider) detachLocked(w *logicWorkflow) logicLiveSet { + p.unsubscribeAllLocked(w) + key := w.key() + delete(p.hookBases, key) delete(p.wf, key) for qk, q := range p.queue { @@ -431,6 +447,8 @@ func (p *LogicProvider) Reset() { live := p.live p.live = map[string]*logicLive{} p.queue = map[string][]*logicQueued{} + p.hookQ = nil + p.hookBases = nil p.mu.Unlock() p.stopAllTimers() @@ -466,13 +484,18 @@ func (p *LogicProvider) stopAllTimers() { } } -func (p *LogicProvider) newHTTPClient() *http.Client { +func (p *LogicProvider) newTransport() *http.Transport { tr := httpclient.NewTransport() tr.Proxy = nil tr.DialContext = httpclient.LoopbackDialer(p.external.Load, ErrLogicDestinationNotPermitted).DialContext + tr.TLSClientConfig = p.tlsConfig() + + return tr +} +func (p *LogicProvider) newHTTPClient() *http.Client { return &http.Client{ - Transport: tr, + Transport: p.newTransport(), CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, } } diff --git a/services/azurearm/rp_logic_actions.go b/services/azurearm/rp_logic_actions.go index ff2ad40c3f..dd610a9d70 100644 --- a/services/azurearm/rp_logic_actions.go +++ b/services/azurearm/rp_logic_actions.go @@ -24,7 +24,7 @@ const ( ) func (rs *logicRunState) runCompose(env *logicEnv, name string, def map[string]any) logicOutcome { - v, err := rs.eval(env, def["inputs"]) + v, err := rs.evalTraced(env, name, logicKInputs, def["inputs"]) if err != nil { return exprFailure(name, err) } @@ -33,7 +33,7 @@ func (rs *logicRunState) runCompose(env *logicEnv, name string, def map[string]a } func (rs *logicRunState) runWait(env *logicEnv, name string, def map[string]any) logicOutcome { - in, err := rs.evalInputs(env, def) + in, err := rs.evalInputs(env, name, def) if err != nil { return exprFailure(name, err) } @@ -52,8 +52,8 @@ func (rs *logicRunState) runWait(env *logicEnv, name string, def map[string]any) return out } -func (rs *logicRunState) evalInputs(env *logicEnv, def map[string]any) (map[string]any, error) { - v, err := rs.eval(env, def["inputs"]) +func (rs *logicRunState) evalInputs(env *logicEnv, name string, def map[string]any) (map[string]any, error) { + v, err := rs.evalTraced(env, name, logicKInputs, def["inputs"]) if err != nil { return nil, err } @@ -114,7 +114,7 @@ func logicUnitDuration(unit string, n int64) (time.Duration, error) { } func (rs *logicRunState) runTerminate(env *logicEnv, name string, def map[string]any) logicOutcome { - in, err := rs.evalInputs(env, def) + in, err := rs.evalInputs(env, name, def) if err != nil { return exprFailure(name, err) } @@ -148,7 +148,7 @@ func (rs *logicRunState) runTerminate(env *logicEnv, name string, def map[string } func (rs *logicRunState) runResponse(env *logicEnv, name string, def map[string]any) logicOutcome { - in, err := rs.evalInputs(env, def) + in, err := rs.evalInputs(env, name, def) if err != nil { return exprFailure(name, err) } @@ -187,7 +187,7 @@ func (rs *logicRunState) runResponse(env *logicEnv, name string, def map[string] rs.live.resp <- logicResponse{status: int(status), headers: headers, body: in[logicKBody]} - out := map[string]any{"statusCode": status, logicKHeaders: mapStrAny(headers)} + out := map[string]any{logicKStatusCode: status, logicKHeaders: mapStrAny(headers)} if b, has := in[logicKBody]; has { out[logicKBody] = b } @@ -643,7 +643,7 @@ func logicZero(typ string) any { } func (rs *logicRunState) runVariable(env *logicEnv, name, typ string, def map[string]any) logicOutcome { - in, err := rs.evalInputs(env, def) + in, err := rs.evalInputs(env, name, def) if err != nil { return exprFailure(name, err) } @@ -821,7 +821,7 @@ func (rs *logicRunState) parseJSONOp(env *logicEnv, raw map[string]any) (any, an } } - return map[string]any{logicKContent: content, "schema": raw["schema"]}, val, nil + return map[string]any{logicKContent: content, logicKSchema: raw["schema"]}, val, nil } func (rs *logicRunState) collectionOp(env *logicEnv, typ string, raw map[string]any) (any, any, error) { @@ -843,7 +843,7 @@ func (rs *logicRunState) collectionOp(env *logicEnv, typ string, raw map[string] res, serr := rs.mapItems(env, arr, func(e *logicEnv) (any, error) { return rs.eval(e, raw["select"]) }) return inputs, res, serr - case "query": + case logicKQuery: inputs["where"] = raw["where"] res, qerr := rs.filterItems(env, arr, raw["where"]) diff --git a/services/azurearm/rp_logic_cert.go b/services/azurearm/rp_logic_cert.go new file mode 100644 index 0000000000..11801b811f --- /dev/null +++ b/services/azurearm/rp_logic_cert.go @@ -0,0 +1,120 @@ +package azurearm + +import ( + "crypto" + "crypto/rsa" + "crypto/sha1" //nolint:gosec // x5t is the SHA-1 certificate thumbprint defined by RFC 7515 and used by Entra + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "errors" + "net/http" + "net/url" + "strings" + "time" + + "github.com/golang-jwt/jwt/v5" + "github.com/google/uuid" + pkcs12 "software.sslmate.com/src/go-pkcs12" +) + +const ( + logicAssertionTTL = 10 * time.Minute + logicCodeBadRequest = "BadRequest" +) + +var errLogicClientCert = errors.New("client certificate failed") + +type logicPFX struct { + leaf *x509.Certificate + key crypto.PrivateKey + tls tls.Certificate +} + +// loadLogicPFX decodes the base64 PFX and password of a ClientCertificate or ActiveDirectoryOAuth block. The error +// never carries the password or the key material; "Could not load private key" is the service's BadRequest text +// (Learn: set-up-security-permissions, client certificate note). +func loadLogicPFX(auth map[string]any) (*logicPFX, error) { + raw, err := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(stringOf(auth["pfx"])), "")) + if err != nil || len(raw) == 0 { + return nil, logicClientCertErr("the pfx is not base64 encoded PFX content") + } + + key, leaf, chain, err := pkcs12.DecodeChain(raw, stringOf(auth["password"])) + if err != nil { + return nil, logicClientCertErr("the pfx content or its password is not valid") + } + + signer, ok := key.(crypto.Signer) + if !ok { + return nil, logicClientCertErr("the pfx private key cannot sign") + } + + der := [][]byte{leaf.Raw} + for _, c := range chain { + der = append(der, c.Raw) + } + + return &logicPFX{leaf: leaf, key: key, tls: tls.Certificate{Certificate: der, PrivateKey: signer, Leaf: leaf}}, nil +} + +func logicClientCertErr(msg string) error { + return &logicClientCertError{msg: "Could not load private key: " + msg} +} + +type logicClientCertError struct{ msg string } + +func (e *logicClientCertError) Error() string { return e.msg } +func (e *logicClientCertError) Unwrap() error { return errLogicClientCert } + +// clientAssertion signs the RS256 client-assertion JWT of the certificate credential type: iss and sub are the +// client id, aud the token endpoint, x5t and x5t#S256 the certificate thumbprints. +func (c *logicPFX) clientAssertion(clientID, audience string, now time.Time) (string, error) { + priv, ok := c.key.(*rsa.PrivateKey) + if !ok { + return "", logicClientCertErr("only RSA keys can sign a client assertion") + } + + tok := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{ + "aud": audience, "iss": clientID, "sub": clientID, "jti": uuid.NewString(), + "nbf": now.Unix(), "iat": now.Unix(), "exp": now.Add(logicAssertionTTL).Unix(), + }) + + s1 := sha1.Sum(c.leaf.Raw) //nolint:gosec // thumbprint only + s256 := sha256.Sum256(c.leaf.Raw) + tok.Header["x5t"] = base64.RawURLEncoding.EncodeToString(s1[:]) + tok.Header["x5t#S256"] = base64.RawURLEncoding.EncodeToString(s256[:]) + + return tok.SignedString(priv) +} + +func (p *LogicProvider) tlsConfig() *tls.Config { + return &tls.Config{MinVersion: tls.VersionTLS12, RootCAs: p.roots.Load()} +} + +// certClient is a one-request client presenting cert, on a transport with the same loopback-gated dialer. +func (p *LogicProvider) certClient(cert *tls.Certificate) *http.Client { + tr := p.newTransport() + tr.TLSClientConfig.Certificates = []tls.Certificate{*cert} + + return &http.Client{ + Transport: tr, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } +} + +// SetOutboundRootCAs sets the roots outbound HTTPS calls verify against (nil: the system roots). Call it before +// the provider is in use. +func (p *LogicProvider) SetOutboundRootCAs(pool *x509.CertPool) { + p.roots.Store(pool) + + p.http.Store(p.newHTTPClient()) +} + +func sameOrigin(a, b string) bool { + ua, errA := url.Parse(a) + ub, errB := url.Parse(b) + + return errA == nil && errB == nil && ua.Scheme == ub.Scheme && ua.Host == ub.Host +} diff --git a/services/azurearm/rp_logic_consts.go b/services/azurearm/rp_logic_consts.go index c13fd148b9..be2d53aae0 100644 --- a/services/azurearm/rp_logic_consts.go +++ b/services/azurearm/rp_logic_consts.go @@ -3,6 +3,15 @@ package azurearm // Property and keyword names shared across the Logic provider and engine. const ( logicKCode = "code" + logicKStatusCode = "statusCode" + logicKNull = "null" + logicKHost = "host" + logicKQuery = "query" + logicKPath = "path" + logicKDelete = "delete" + logicKParameters = "parameters" + logicKDefault = "default" + logicKDescription = "description" logicKBody = "body" logicKOutputs = "outputs" logicKInputs = "inputs" diff --git a/services/azurearm/rp_logic_crud.go b/services/azurearm/rp_logic_crud.go index d788224db3..5c3830715a 100644 --- a/services/azurearm/rp_logic_crud.go +++ b/services/azurearm/rp_logic_crud.go @@ -243,6 +243,10 @@ func (p *LogicProvider) reconcileTriggersLocked(w *logicWorkflow, now time.Time) for name := range w.Triggers { if _, ok := defs[name]; !ok { + if h := w.Triggers[name].Hook; h != nil && !w.Triggers[name].HookPending { + p.queueHookLocked(p.hookJobLocked(w, name, false, h)) + } + delete(w.Triggers, name) } } diff --git a/services/azurearm/rp_logic_def.go b/services/azurearm/rp_logic_def.go index 90be49bd1d..3ff21ce513 100644 --- a/services/azurearm/rp_logic_def.go +++ b/services/azurearm/rp_logic_def.go @@ -158,6 +158,10 @@ func validateLogicTrigger(name string, t any) error { switch typ { case logicTrigRecurrence: return validateLogicRecurrence(name, m) + case logicTrigHTTP: + return validateLogicHTTPTrigger(name, m) + case logicTrigWebhook: + return validateLogicWebhookTrigger(name, m) case logicTrigRequest, logicTrigManual: return validateLogicRequestTrigger(name, m) } @@ -506,7 +510,7 @@ func validateLogicExpressions(v any) error { return checkLogicTemplate(t) case map[string]any: for k, x := range t { - if k == "schema" || k == logicKMetadata { + if k == logicKSchema || k == logicKMetadata { continue } diff --git a/services/azurearm/rp_logic_exec.go b/services/azurearm/rp_logic_exec.go index 1189fa3736..677c53bc7a 100644 --- a/services/azurearm/rp_logic_exec.go +++ b/services/azurearm/rp_logic_exec.go @@ -91,12 +91,16 @@ type logicRunState struct { iters map[string][]*logicEnv wfKey string wfName string + + callbackURL string + budget logicRunBudget } type logicEvalCtx struct { - rs *logicRunState - env *logicEnv - now func() time.Time + rs *logicRunState + env *logicEnv + now func() time.Time + trace *logicTracer } func (rs *logicRunState) evalCtx(env *logicEnv) *logicEvalCtx { @@ -390,7 +394,7 @@ func (rs *logicRunState) dispatch(env *logicEnv, name, typ string, def map[strin return rs.runForeach(env, name, def) case logicActUntil: return rs.runUntil(env, name, def) - case "parsejson", "select", "query", "join", logicTypeTable: + case "parsejson", "select", logicKQuery, "join", logicTypeTable: return rs.runDataOp(env, name, typ, def) } diff --git a/services/azurearm/rp_logic_expr.go b/services/azurearm/rp_logic_expr.go index 3dbcb25254..e8ee432bb7 100644 --- a/services/azurearm/rp_logic_expr.go +++ b/services/azurearm/rp_logic_expr.go @@ -231,7 +231,7 @@ func (p *exprParser) parseIdent() (*logicExpr, error) { return &logicExpr{kind: exprLit, lit: true}, nil case logicLitFalse: return &logicExpr{kind: exprLit, lit: false}, nil - case "null": + case logicKNull: return &logicExpr{kind: exprLit, lit: nil}, nil } @@ -435,12 +435,17 @@ func matchingBrace(s string, open int) int { func evalLogicValue(v any, c *logicEvalCtx) (any, error) { switch t := v.(type) { case string: - return evalLogicTemplate(t, c) + return evalTracedTemplate(t, c) case map[string]any: out := make(map[string]any, len(t)) for k, x := range t { + c.pushPath(k) + r, err := evalLogicValue(x, c) + + c.popPath() + if err != nil { return nil, err } @@ -453,7 +458,12 @@ func evalLogicValue(v any, c *logicEvalCtx) (any, error) { out := make([]any, len(t)) for i, x := range t { + c.pushPath(indexSeg(i)) + r, err := evalLogicValue(x, c) + + c.popPath() + if err != nil { return nil, err } @@ -466,3 +476,16 @@ func evalLogicValue(v any, c *logicEvalCtx) (any, error) { return normLogic(v), nil } + +func evalTracedTemplate(s string, c *logicEvalCtx) (any, error) { + if c.trace == nil || !strings.Contains(s, "@") { + return evalLogicTemplate(s, c) + } + + c.trace.beginRoot() + + v, err := evalLogicTemplate(s, c) + c.trace.endRoot(s, v, err) + + return v, err +} diff --git a/services/azurearm/rp_logic_funcs.go b/services/azurearm/rp_logic_funcs.go index 0a0ba7c612..2315c620c7 100644 --- a/services/azurearm/rp_logic_funcs.go +++ b/services/azurearm/rp_logic_funcs.go @@ -52,7 +52,7 @@ func eagerLogic(name string, minArgs, maxArgs int, f func(a []any) (any, error)) } } -func (c *logicEvalCtx) eval(n *logicExpr) (any, error) { +func (c *logicEvalCtx) evalNode(n *logicExpr) (any, error) { switch n.kind { case exprLit: return n.lit, nil diff --git a/services/azurearm/rp_logic_hook.go b/services/azurearm/rp_logic_hook.go new file mode 100644 index 0000000000..40485954cd --- /dev/null +++ b/services/azurearm/rp_logic_hook.go @@ -0,0 +1,345 @@ +package azurearm + +import ( + "crypto/sha256" + "encoding/hex" + "encoding/json/v2" + "log/slog" + "maps" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "unicode" + + "github.com/blackbirdworks/gopherstack/pkgs/jsonx" + "github.com/blackbirdworks/gopherstack/pkgs/logger" +) + +const ( + logicMaxPort = 65535 + logicMaxHostLen = 253 + logicTrigWebhook = "httpwebhook" + logicKSubscribe = "subscribe" +) + +// logicHookRec remembers a successful HttpWebhook subscribe so the matching unsubscribe can be sent later, even +// after the trigger or workflow is gone. +type logicHookRec struct { + Unsub map[string]any `json:"unsub,omitempty"` + Fingerprint string `json:"fingerprint"` + Callback string `json:"callback"` +} + +type logicHookJob struct { + call map[string]any + params map[string]any + def map[string]any + unsub map[string]any + wfKey string + wfName string + trigger string + callback string + fingerprint string + subscribe bool +} + +func validateLogicWebhookTrigger(name string, m map[string]any) error { + in, _ := objectOf(m["inputs"]) + + for _, k := range []string{logicKSubscribe, "unsubscribe"} { + call, ok := objectOf(in[k]) + if !ok { + if k == logicKSubscribe { + return invalidTemplate( + "the trigger '%s' of type 'HttpWebhook' requires 'subscribe' in its inputs", + name, + ) + } + + continue + } + + if !logicHTTPMethod(stringOf(call["method"])) || stringOf(call["uri"]) == "" { + return invalidTemplate("the trigger '%s' %s call requires a valid 'method' and a 'uri'", name, k) + } + } + + return nil +} + +func logicHTTPMethod(m string) bool { + switch strings.ToUpper(m) { + case http.MethodGet, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodHead: + return true + } + + return false +} + +func hookFingerprint(def map[string]any) string { + in, _ := objectOf(def["inputs"]) + + raw, err := json.Marshal(in[logicKSubscribe], jsonx.V1()) + if err != nil { + return "" + } + + sum := sha256.Sum256(raw) + + return hex.EncodeToString(sum[:]) +} + +// noteBase remembers the address the caller that wrote this workflow reached the emulator on; webhook callback +// URLs for the workflow are built from it, so one caller's Host header only affects the resource it just wrote. +// A base that is not a plain https host[:port] is ignored. +func (p *LogicProvider) noteBase(wfKey, base string, port int) { + p.mu.Lock("noteBase") + defer p.mu.Unlock() + + p.hookPort = port + + if validBase(base) { + if p.hookBases == nil { + p.hookBases = map[string]string{} + } + + p.hookBases[wfKey] = base + } +} + +func (p *LogicProvider) baseForLocked(wfKey string) string { + if b, ok := p.hookBases[wfKey]; ok { + return b + } + + return "https://" + net.JoinHostPort("localhost", strconv.Itoa(p.hookPort)) +} + +// validBase accepts only https://host[:port] with a DNS name or IP literal host: no userinfo, path or query. +func validBase(base string) bool { + u, err := url.Parse(base) + if err != nil || u.Scheme != logicSchemeHTTPS || u.User != nil || u.Path != "" || u.RawQuery != "" || + u.Fragment != "" || u.Opaque != "" { + return false + } + + return validPort(u.Port()) && validHostName(u.Hostname()) +} + +func validPort(port string) bool { + if port == "" { + return true + } + + n, err := strconv.Atoi(port) + + return err == nil && n >= 1 && n <= logicMaxPort +} + +func validHostName(host string) bool { + if host == "" || len(host) > logicMaxHostLen { + return false + } + + if net.ParseIP(host) != nil { + return true + } + + return !strings.ContainsFunc(host, func(r rune) bool { + return r != '.' && r != '-' && r != '_' && !unicode.IsDigit(r) && (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') + }) +} + +func (p *LogicProvider) queueHookLocked(j *logicHookJob) { + p.hookQ = append(p.hookQ, j) + + if !p.hookRun { + p.hookRun = true + + p.wg.Go(p.drainHooks) + } +} + +func (p *LogicProvider) hookJobLocked(w *logicWorkflow, name string, subscribe bool, rec *logicHookRec) *logicHookJob { + def := w.triggerDef(name) + in, _ := objectOf(def["inputs"]) + unsub, _ := objectOf(in["unsubscribe"]) + + j := &logicHookJob{ + params: effectiveLogicParams(w), def: w.Definition, wfKey: w.key(), wfName: w.Name, trigger: name, + subscribe: subscribe, fingerprint: hookFingerprint(def), unsub: unsub, + } + + if subscribe { + j.call, _ = objectOf(in[logicKSubscribe]) + j.callback, _ = w.callbackURL(p.baseForLocked(w.key()), name, "Primary", nil)["value"].(string) + + return j + } + + j.call, j.callback = rec.Unsub, rec.Callback + + return j +} + +// syncWebhooksLocked queues the subscribe and unsubscribe calls that bring every HttpWebhook trigger in line with +// the workflow and trigger state: subscribed while both are enabled and the subscribe call is unchanged. +func (p *LogicProvider) syncWebhooksLocked(w *logicWorkflow) { + for name, ts := range w.Triggers { + if ts.HookPending { + continue + } + + def := w.triggerDef(name) + want := typeOf(def) == logicTrigWebhook && w.State == logicStateEnabled && ts.State == logicStateEnabled + + switch { + case ts.Hook != nil && (!want || ts.Hook.Fingerprint != hookFingerprint(def)): + ts.HookPending = true + + p.queueHookLocked(p.hookJobLocked(w, name, false, ts.Hook)) + case ts.Hook == nil && want: + ts.HookPending = true + + p.queueHookLocked(p.hookJobLocked(w, name, true, nil)) + } + } +} + +// unsubscribeAllLocked queues the unsubscribe of every subscribed trigger of a workflow being removed. +func (p *LogicProvider) unsubscribeAllLocked(w *logicWorkflow) { + for name, ts := range w.Triggers { + if ts.Hook != nil && !ts.HookPending { + p.queueHookLocked(p.hookJobLocked(w, name, false, ts.Hook)) + } + } +} + +func (p *LogicProvider) drainHooks() { + for { + p.mu.Lock("drainHooks") + + if len(p.hookQ) == 0 || p.rootCtx.Err() != nil { + p.hookQ, p.hookRun = nil, false + p.mu.Unlock() + + return + } + + j := p.hookQ[0] + p.hookQ = p.hookQ[1:] + p.mu.Unlock() + + err := p.runHook(j) + + p.mu.Lock("hookResult") + p.applyHookLocked(j, err) + p.mu.Unlock() + } +} + +// runHook sends one subscribe or unsubscribe call outside the provider lock, through the Http action's outbound +// rules (loopback-gated unless external hosts are allowed). +func (p *LogicProvider) runHook(j *logicHookJob) error { + if j.call == nil { + return nil + } + + plan := logicPollPlan{params: j.params, wfDef: j.def, wfName: j.wfName} + rs := p.pollState(plan, p.currentClock().Now) + rs.callbackURL = j.callback + env := &logicEnv{local: map[string]*logicActionRec{}} + + in, err := rs.evalInputs(env, j.trigger, map[string]any{"inputs": j.call}) + if err != nil { + return err + } + + pol, err := parseRetryPolicy(in) + if err != nil { + return err + } + + req, err := rs.buildHTTPRequest(in, map[string]any{}) + if err != nil { + return err + } + + req.async = false + + resp, _, err := rs.doHTTP(req, pol, logicHTTPTimeout) + if err != nil { + return err + } + + if resp.status >= logicHTTPErrorFloor { + return inputErr( + "the %s call answered %d", + hookVerb(j.subscribe), + resp.status, + ) + } + + return nil +} + +func (p *LogicProvider) applyHookLocked(j *logicHookJob, err error) { + w, ok := p.wf[j.wfKey] + if !ok { + p.orphanUnsubscribeLocked(j, err) + + return + } + + ts, ok := w.Triggers[j.trigger] + if !ok { + p.orphanUnsubscribeLocked(j, err) + + return + } + + ts.HookPending = false + + switch { + case err != nil && j.subscribe: + p.recordPollFailure(w, logicFire{trigger: j.trigger, scheduled: p.clock.Now().UTC()}, p.clock.Now().UTC(), err) + case err != nil: + logger.Load(p.rootCtx).Log(p.rootCtx, slog.LevelWarn, "azurearm: logic webhook unsubscribe failed", + "workflow", j.wfName, "trigger", j.trigger) + + ts.Hook = nil + case j.subscribe: + ts.Hook = &logicHookRec{Fingerprint: j.fingerprint, Callback: j.callback} + if len(j.unsub) > 0 { + ts.Hook.Unsub = maps.Clone(j.unsub) + } + default: + ts.Hook = nil + } + + if err == nil || !j.subscribe { + p.syncWebhooksLocked(w) + } +} + +// orphanUnsubscribeLocked undoes a subscribe that succeeded after its workflow or trigger was removed. +func (p *LogicProvider) orphanUnsubscribeLocked(j *logicHookJob, err error) { + if err != nil || !j.subscribe || len(j.unsub) == 0 { + return + } + + p.queueHookLocked(&logicHookJob{ + call: j.unsub, callback: j.callback, params: j.params, def: j.def, wfKey: j.wfKey, wfName: j.wfName, + trigger: j.trigger, + }) +} + +func hookVerb(subscribe bool) string { + if subscribe { + return logicKSubscribe + } + + return "unsubscribe" +} diff --git a/services/azurearm/rp_logic_http.go b/services/azurearm/rp_logic_http.go index 8e1c1fd7ce..c6422b5133 100644 --- a/services/azurearm/rp_logic_http.go +++ b/services/azurearm/rp_logic_http.go @@ -3,6 +3,7 @@ package azurearm import ( "bytes" "context" + "crypto/tls" "encoding/base64" "encoding/json/v2" "errors" @@ -87,7 +88,7 @@ func parseRetryPolicy(in map[string]any) (logicRetryPolicy, error) { } func (rs *logicRunState) runHTTP(env *logicEnv, name string, def map[string]any) logicOutcome { - in, err := rs.evalInputs(env, def) + in, err := rs.evalInputs(env, name, def) if err != nil { return exprFailure(name, err) } @@ -113,13 +114,19 @@ func (rs *logicRunState) runHTTP(env *logicEnv, name string, def map[string]any) req, err := rs.buildHTTPRequest(in, def) if err != nil { code := logicCodeInvalidTmpl - if errors.Is(err, errLogicTokenRequest) { + + switch { + case errors.Is(err, errLogicTokenRequest): code = logicCodeActionFailed + case errors.Is(err, errLogicClientCert): + code = logicCodeBadRequest } return failOutcome(code, err.Error()) } + req.rec = rs.currentRec(env, name) + resp, history, err := rs.doHTTP(req, policy, timeout) out := logicOutcome{inputs: httpInputs(in), hasIn: true} @@ -186,7 +193,7 @@ func setRequestHeaders(h http.Header, in map[string]any, method string) { func (rs *logicRunState) buildHTTPRequest(in, def map[string]any) (*logicHTTPRequest, error) { method := strings.ToUpper(stringOf(in["method"])) switch method { - case "GET", "PUT", "POST", "PATCH", "DELETE", "HEAD": + case http.MethodGet, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodHead: default: return nil, inputErr("the HTTP method '%s' is not valid", stringOf(in["method"])) } @@ -224,7 +231,10 @@ func (rs *logicRunState) buildHTTPRequest(in, def map[string]any) (*logicHTTPReq if !strings.EqualFold(stringOf(def["operationOptions"]), "SuppressWorkflowHeaders") { req.header.Set("X-Ms-Workflow-Name", rs.wfName) - req.header.Set("X-Ms-Workflow-Run-Id", rs.run.Name) + + if rs.run.Name != "" { + req.header.Set("X-Ms-Workflow-Run-Id", rs.run.Name) + } } return req, nil @@ -239,6 +249,13 @@ func (rs *logicRunState) applyHTTPAuth(req *logicHTTPRequest, auth map[string]an } req.header.Set("Authorization", tok) + case "clientcertificate": + pfx, err := loadLogicPFX(auth) + if err != nil { + return err + } + + req.cert = &pfx.tls case "basic": cred := stringOf(auth["username"]) + ":" + stringOf(auth["password"]) req.header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(cred))) @@ -253,6 +270,8 @@ func (rs *logicRunState) applyHTTPAuth(req *logicHTTPRequest, auth map[string]an } type logicHTTPRequest struct { + cert *tls.Certificate + rec *logicActionRec body any header http.Header method string @@ -267,7 +286,7 @@ type logicHTTPResponse struct { } func (r *logicHTTPResponse) outputs() map[string]any { - out := map[string]any{"statusCode": int64(r.status), logicKHeaders: r.headers} + out := map[string]any{logicKStatusCode: int64(r.status), logicKHeaders: r.headers} if r.body != nil { out[logicKBody] = r.body } @@ -289,7 +308,7 @@ func (rs *logicRunState) doHTTP(req *logicHTTPRequest, pol logicRetryPolicy, tim for attempt := 0; ; attempt++ { started := rs.clock() - resp, err := rs.p.sendHTTP(ctx, req) + resp, err := rs.send(ctx, req) retryable := err != nil && ctx.Err() == nil || resp != nil && retryableStatus(resp.status) if !retryable || attempt >= pol.count { @@ -372,7 +391,14 @@ func (p *LogicProvider) sendHTTP(ctx context.Context, r *logicHTTPRequest) (*log req.Header = r.header.Clone() - resp, err := p.http.Do(req) + client := p.http.Load() + + if r.cert != nil { + client = p.certClient(r.cert) + defer client.CloseIdleConnections() + } + + resp, err := client.Do(req) if err != nil { return nil, err } @@ -424,7 +450,7 @@ func dropOmittedHeaders(h http.Header, method string) { func omittedHeader(lk, method string) bool { switch lk { - case acaRuleAllow, "cookie", "expires", "host", "last-modified", "origin", "set-cookie", "transfer-encoding": + case acaRuleAllow, "cookie", "expires", logicKHost, "last-modified", "origin", "set-cookie", "transfer-encoding": return true case "content-disposition", "content-encoding", "content-type": return method == http.MethodGet @@ -453,9 +479,12 @@ func (rs *logicRunState) pollAsync(ctx context.Context, req *logicHTTPRequest, r return nil, context.Cause(ctx) } - poll := &logicHTTPRequest{method: http.MethodGet, url: loc, header: pollHeaders(req, loc)} + poll := &logicHTTPRequest{method: http.MethodGet, url: loc, header: pollHeaders(req, loc), rec: req.rec} + if sameOrigin(req.url, loc) { + poll.cert = req.cert + } - next, err := rs.p.sendHTTP(ctx, poll) + next, err := rs.send(ctx, poll) if err != nil { return nil, err } diff --git a/services/azurearm/rp_logic_locales.go b/services/azurearm/rp_logic_locales.go new file mode 100644 index 0000000000..389750de2d --- /dev/null +++ b/services/azurearm/rp_logic_locales.go @@ -0,0 +1,93 @@ +package azurearm + +import ( + _ "embed" // locale table + "errors" + "fmt" + "slices" + "strings" +) + +var errLogicLocaleRow = errors.New("malformed locale row") + +//go:embed rp_logic_locales.txt +var logicLocaleTable string + +const ( + logicLocaleCols = 9 + logicLocaleMonths = 12 + logicLocaleDays = 7 + logicLocaleStd = "dDfFgGtT" +) + +//nolint:gochecknoglobals // static locale tables decoded once from the embedded CLDR export +var logicLocales = mustDecodeLogicLocales(logicLocaleTable) + +func mustDecodeLogicLocales(table string) map[string]logicLocale { + out, err := decodeLogicLocales(table) + if err != nil { + panic(err) + } + + return out +} + +// decodeLogicLocales parses the embedded table; a malformed row is an error, never a silently missing culture. +func decodeLogicLocales(table string) (map[string]logicLocale, error) { + out := map[string]logicLocale{} + + for n, line := range strings.Split(table, "\n") { + if line == "" || line[0] == '#' { + continue + } + + key, l, err := decodeLogicLocaleRow(line) + if err != nil { + return nil, fmt.Errorf("logic locale table line %d: %w", n+1, err) + } + + out[key] = l + } + + return out, nil +} + +func decodeLogicLocaleRow(line string) (string, logicLocale, error) { + cols := strings.Split(line, "\t") + if len(cols) != logicLocaleCols { + return "", logicLocale{}, fmt.Errorf("%w: %d columns, want %d", errLogicLocaleRow, len(cols), logicLocaleCols) + } + + l := logicLocale{am: cols[5], pm: cols[6], std: map[string]string{}} + + for _, f := range []struct { + src string + dst []string + want int + }{ + {cols[1], l.months[:], logicLocaleMonths}, + {cols[2], l.abbrMonths[:], logicLocaleMonths}, + {cols[3], l.days[:], logicLocaleDays}, + {cols[4], l.abbrDays[:], logicLocaleDays}, + } { + parts := strings.Split(f.src, "|") + if len(parts) != f.want || slices.Contains(parts, "") { + return "", logicLocale{}, fmt.Errorf("%w: %q is not %d names", errLogicLocaleRow, f.src, f.want) + } + + copy(f.dst, parts) + } + + std := strings.Split(cols[7], "|") + if len(std) != len(logicLocaleStd) { + return "", logicLocale{}, fmt.Errorf("%w: %d standard patterns", errLogicLocaleRow, len(std)) + } + + for i, p := range std { + l.std[logicLocaleStd[i:i+1]] = p + } + + l.parse = strings.Split(cols[8], "|") + + return cols[0], l, nil +} diff --git a/services/azurearm/rp_logic_locales.txt b/services/azurearm/rp_logic_locales.txt new file mode 100644 index 0000000000..aa1b123a06 --- /dev/null +++ b/services/azurearm/rp_logic_locales.txt @@ -0,0 +1,20 @@ +# Generated from CLDR gregorian data (golang.org/x/text v0.44.0 date tables). Columns: key, months, abbreviated months, days, abbreviated days, AM, PM, standard patterns d D f F g G t T, parse patterns; lists are separated by |. +en-us January|February|March|April|May|June|July|August|September|October|November|December Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday Sun|Mon|Tue|Wed|Thu|Fri|Sat AM PM M/d/yyyy|dddd, MMMM d, yyyy|dddd, MMMM d, yyyy h:mm tt|dddd, MMMM d, yyyy h:mm:ss tt|M/d/yyyy h:mm tt|M/d/yyyy h:mm:ss tt|h:mm tt|h:mm:ss tt M/d/yyyy|MMM d, yyyy|MMMM d, yyyy|dddd, MMMM d, yyyy +en-gb January|February|March|April|May|June|July|August|September|October|November|December Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday Sun|Mon|Tue|Wed|Thu|Fri|Sat am pm dd/MM/yyyy|dddd, d MMMM yyyy|dddd, d MMMM yyyy HH:mm|dddd, d MMMM yyyy HH:mm:ss|dd/MM/yyyy HH:mm|dd/MM/yyyy HH:mm:ss|HH:mm|HH:mm:ss dd/MM/yyyy|d MMM yyyy|d MMMM yyyy|dddd, d MMMM yyyy +fr-fr janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre janv.|févr.|mars|avr.|mai|juin|juil.|août|sept.|oct.|nov.|déc. dimanche|lundi|mardi|mercredi|jeudi|vendredi|samedi dim.|lun.|mar.|mer.|jeu.|ven.|sam. AM PM dd/MM/yyyy|dddd d MMMM yyyy|dddd d MMMM yyyy HH:mm|dddd d MMMM yyyy HH:mm:ss|dd/MM/yyyy HH:mm|dd/MM/yyyy HH:mm:ss|HH:mm|HH:mm:ss dd/MM/yyyy|d MMM yyyy|d MMMM yyyy|dddd d MMMM yyyy +es-es enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre ene.|feb.|mar.|abr.|may.|jun.|jul.|ago.|sept.|oct.|nov.|dic. domingo|lunes|martes|miércoles|jueves|viernes|sábado dom.|lun.|mar.|mié.|jue.|vie.|sáb. a. m. p. m. d/M/yyyy|dddd, d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy H:mm|dddd, d 'de' MMMM 'de' yyyy H:mm:ss|d/M/yyyy H:mm|d/M/yyyy H:mm:ss|H:mm|H:mm:ss d/M/yyyy|d MMM yyyy|d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy +de-de Januar|Februar|März|April|Mai|Juni|Juli|August|September|Oktober|November|Dezember Jan.|Feb.|März|Apr.|Mai|Juni|Juli|Aug.|Sep.|Okt.|Nov.|Dez. Sonntag|Montag|Dienstag|Mittwoch|Donnerstag|Freitag|Samstag So.|Mo.|Di.|Mi.|Do.|Fr.|Sa. AM PM dd.MM.yyyy|dddd, d. MMMM yyyy|dddd, d. MMMM yyyy HH:mm|dddd, d. MMMM yyyy HH:mm:ss|dd.MM.yyyy HH:mm|dd.MM.yyyy HH:mm:ss|HH:mm|HH:mm:ss dd.MM.yyyy|d. MMMM yyyy|dddd, d. MMMM yyyy +it-it gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre gen|feb|mar|apr|mag|giu|lug|ago|set|ott|nov|dic domenica|lunedì|martedì|mercoledì|giovedì|venerdì|sabato dom|lun|mar|mer|gio|ven|sab AM PM dd/MM/yyyy|dddd d MMMM yyyy|dddd d MMMM yyyy HH:mm|dddd d MMMM yyyy HH:mm:ss|dd/MM/yyyy HH:mm|dd/MM/yyyy HH:mm:ss|HH:mm|HH:mm:ss dd/MM/yyyy|d MMM yyyy|d MMMM yyyy|dddd d MMMM yyyy +pt-br janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez domingo|segunda-feira|terça-feira|quarta-feira|quinta-feira|sexta-feira|sábado dom|seg|ter|qua|qui|sex|sáb AM PM dd/MM/yyyy|dddd, d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy HH:mm|dddd, d 'de' MMMM 'de' yyyy HH:mm:ss|dd/MM/yyyy HH:mm|dd/MM/yyyy HH:mm:ss|HH:mm|HH:mm:ss dd/MM/yyyy|d 'de' MMM 'de' yyyy|d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy +pt-pt janeiro|fevereiro|março|abril|maio|junho|julho|agosto|setembro|outubro|novembro|dezembro jan|fev|mar|abr|mai|jun|jul|ago|set|out|nov|dez domingo|segunda-feira|terça-feira|quarta-feira|quinta-feira|sexta-feira|sábado domingo|segunda|terça|quarta|quinta|sexta|sábado a.m. p.m. dd/MM/yyyy|dddd, d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy HH:mm|dddd, d 'de' MMMM 'de' yyyy HH:mm:ss|dd/MM/yyyy HH:mm|dd/MM/yyyy HH:mm:ss|HH:mm|HH:mm:ss dd/MM/yyyy|d 'de' MMMM 'de' yyyy|dddd, d 'de' MMMM 'de' yyyy +nl-nl januari|februari|maart|april|mei|juni|juli|augustus|september|oktober|november|december jan.|feb.|mrt.|apr.|mei|jun.|jul.|aug.|sep.|okt.|nov.|dec. zondag|maandag|dinsdag|woensdag|donderdag|vrijdag|zaterdag zo|ma|di|wo|do|vr|za a.m. p.m. dd-MM-yyyy|dddd d MMMM yyyy|dddd d MMMM yyyy HH:mm|dddd d MMMM yyyy HH:mm:ss|dd-MM-yyyy HH:mm|dd-MM-yyyy HH:mm:ss|HH:mm|HH:mm:ss dd-MM-yyyy|d MMM yyyy|d MMMM yyyy|dddd d MMMM yyyy +sv-se januari|februari|mars|april|maj|juni|juli|augusti|september|oktober|november|december jan.|feb.|mars|apr.|maj|juni|juli|aug.|sep.|okt.|nov.|dec. söndag|måndag|tisdag|onsdag|torsdag|fredag|lördag sön|mån|tis|ons|tors|fre|lör fm em yyyy-MM-dd|dddd d MMMM yyyy|dddd d MMMM yyyy HH:mm|dddd d MMMM yyyy HH:mm:ss|yyyy-MM-dd HH:mm|yyyy-MM-dd HH:mm:ss|HH:mm|HH:mm:ss yyyy-MM-dd|d MMM yyyy|d MMMM yyyy|dddd d MMMM yyyy +da-dk januar|februar|marts|april|maj|juni|juli|august|september|oktober|november|december jan.|feb.|mar.|apr.|maj|jun.|jul.|aug.|sep.|okt.|nov.|dec. søndag|mandag|tirsdag|onsdag|torsdag|fredag|lørdag søn.|man.|tir.|ons.|tor.|fre.|lør. AM PM dd/MM/yyyy|dddd 'den' d. MMMM yyyy|dddd 'den' d. MMMM yyyy HH.mm|dddd 'den' d. MMMM yyyy HH.mm.ss|dd/MM/yyyy HH.mm|dd/MM/yyyy HH.mm.ss|HH.mm|HH.mm.ss dd/MM/yyyy|d. MMM yyyy|d. MMMM yyyy|dddd 'den' d. MMMM yyyy +nb-no januar|februar|mars|april|mai|juni|juli|august|september|oktober|november|desember jan.|feb.|mar.|apr.|mai|jun.|jul.|aug.|sep.|okt.|nov.|des. søndag|mandag|tirsdag|onsdag|torsdag|fredag|lørdag søn.|man.|tir.|ons.|tor.|fre.|lør. a.m. p.m. dd.MM.yyyy|dddd d. MMMM yyyy|dddd d. MMMM yyyy HH:mm|dddd d. MMMM yyyy HH:mm:ss|dd.MM.yyyy HH:mm|dd.MM.yyyy HH:mm:ss|HH:mm|HH:mm:ss dd.MM.yyyy|d. MMM yyyy|d. MMMM yyyy|dddd d. MMMM yyyy +fi-fi tammikuuta|helmikuuta|maaliskuuta|huhtikuuta|toukokuuta|kesäkuuta|heinäkuuta|elokuuta|syyskuuta|lokakuuta|marraskuuta|joulukuuta tammik.|helmik.|maalisk.|huhtik.|toukok.|kesäk.|heinäk.|elok.|syysk.|lokak.|marrask.|jouluk. sunnuntaina|maanantaina|tiistaina|keskiviikkona|torstaina|perjantaina|lauantaina su|ma|ti|ke|to|pe|la ap. ip. d.M.yyyy|dddd d. MMMM yyyy|dddd d. MMMM yyyy H.mm|dddd d. MMMM yyyy H.mm.ss|d.M.yyyy H.mm|d.M.yyyy H.mm.ss|H.mm|H.mm.ss d.M.yyyy|d. MMMM yyyy|dddd d. MMMM yyyy +pl-pl stycznia|lutego|marca|kwietnia|maja|czerwca|lipca|sierpnia|września|października|listopada|grudnia sty|lut|mar|kwi|maj|cze|lip|sie|wrz|paź|lis|gru niedziela|poniedziałek|wtorek|środa|czwartek|piątek|sobota niedz.|pon.|wt.|śr.|czw.|pt.|sob. AM PM dd.MM.yyyy|dddd, d MMMM yyyy|dddd, d MMMM yyyy HH:mm|dddd, d MMMM yyyy HH:mm:ss|dd.MM.yyyy HH:mm|dd.MM.yyyy HH:mm:ss|HH:mm|HH:mm:ss dd.MM.yyyy|d MMM yyyy|d MMMM yyyy|dddd, d MMMM yyyy +ja-jp 1月|2月|3月|4月|5月|6月|7月|8月|9月|10月|11月|12月 1月|2月|3月|4月|5月|6月|7月|8月|9月|10月|11月|12月 日曜日|月曜日|火曜日|水曜日|木曜日|金曜日|土曜日 日|月|火|水|木|金|土 午前 午後 yyyy/MM/dd|yyyy年M月d日dddd|yyyy年M月d日dddd H:mm|yyyy年M月d日dddd H:mm:ss|yyyy/MM/dd H:mm|yyyy/MM/dd H:mm:ss|H:mm|H:mm:ss yyyy/MM/dd|yyyy年M月d日|yyyy年M月d日dddd +zh-cn 一月|二月|三月|四月|五月|六月|七月|八月|九月|十月|十一月|十二月 1月|2月|3月|4月|5月|6月|7月|8月|9月|10月|11月|12月 星期日|星期一|星期二|星期三|星期四|星期五|星期六 周日|周一|周二|周三|周四|周五|周六 上午 下午 yyyy/M/d|yyyy年M月d日dddd|yyyy年M月d日dddd tth:mm|yyyy年M月d日dddd tth:mm:ss|yyyy/M/d tth:mm|yyyy/M/d tth:mm:ss|tth:mm|tth:mm:ss yyyy/M/d|yyyy年M月d日|yyyy年M月d日dddd +ko-kr 1월|2월|3월|4월|5월|6월|7월|8월|9월|10월|11월|12월 1월|2월|3월|4월|5월|6월|7월|8월|9월|10월|11월|12월 일요일|월요일|화요일|수요일|목요일|금요일|토요일 일|월|화|수|목|금|토 오전 오후 yyyy. M. d.|yyyy년 M월 d일 dddd|yyyy년 M월 d일 dddd tt h:mm|yyyy년 M월 d일 dddd tt h:mm:ss|yyyy. M. d. tt h:mm|yyyy. M. d. tt h:mm:ss|tt h:mm|tt h:mm:ss yyyy. M. d.|yyyy년 M월 d일|yyyy년 M월 d일 dddd +ru-ru января|февраля|марта|апреля|мая|июня|июля|августа|сентября|октября|ноября|декабря янв.|февр.|мар.|апр.|мая|июн.|июл.|авг.|сент.|окт.|нояб.|дек. воскресенье|понедельник|вторник|среда|четверг|пятница|суббота вс|пн|вт|ср|чт|пт|сб AM PM dd.MM.yyyy|dddd, d MMMM yyyy 'г'.|dddd, d MMMM yyyy 'г'. H:mm|dddd, d MMMM yyyy 'г'. H:mm:ss|dd.MM.yyyy H:mm|dd.MM.yyyy H:mm:ss|H:mm|H:mm:ss dd.MM.yyyy|d MMM yyyy 'г'.|d MMMM yyyy 'г'.|dddd, d MMMM yyyy 'г'. +tr-tr Ocak|Şubat|Mart|Nisan|Mayıs|Haziran|Temmuz|Ağustos|Eylül|Ekim|Kasım|Aralık Oca|Şub|Mar|Nis|May|Haz|Tem|Ağu|Eyl|Eki|Kas|Ara Pazar|Pazartesi|Salı|Çarşamba|Perşembe|Cuma|Cumartesi Paz|Pzt|Sal|Çar|Per|Cum|Cmt ÖÖ ÖS d.MM.yyyy|d MMMM yyyy dddd|d MMMM yyyy dddd HH:mm|d MMMM yyyy dddd HH:mm:ss|d.MM.yyyy HH:mm|d.MM.yyyy HH:mm:ss|HH:mm|HH:mm:ss d.MM.yyyy|d MMM yyyy|d MMMM yyyy|d MMMM yyyy dddd diff --git a/services/azurearm/rp_logic_oauth.go b/services/azurearm/rp_logic_oauth.go index 73d2e3d4e1..fe91b877fd 100644 --- a/services/azurearm/rp_logic_oauth.go +++ b/services/azurearm/rp_logic_oauth.go @@ -1,6 +1,7 @@ package azurearm import ( + "context" "encoding/json/v2" "errors" "fmt" @@ -9,8 +10,6 @@ import ( "net/url" "strings" - "context" - "github.com/blackbirdworks/gopherstack/pkgs/jsonx" ) @@ -30,14 +29,9 @@ type logicOAuthToken struct { // Secret credential type and returns the Authorization header value. The request goes through the provider's // loopback-gated client, so only an authority inside the emulator is reachable unless external hosts are allowed. func (rs *logicRunState) fetchOAuthToken(auth map[string]any) (string, error) { - if ct := stringOf(auth["credentialType"]); ct != "" && !strings.EqualFold(ct, "Secret") { - return "", inputErr("the ActiveDirectoryOAuth credential type '%s' is not supported by this emulator", ct) - } - - for _, k := range []string{"tenant", "audience", fieldClientID, apimCSecret} { - if stringOf(auth[k]) == "" { - return "", inputErr("the ActiveDirectoryOAuth authentication requires '%s'", k) - } + cert, err := oauthCredential(auth) + if err != nil { + return "", err } authority := orStr(stringOf(auth["authority"]), logicOAuthDefaultAuthority) @@ -45,7 +39,11 @@ func (rs *logicRunState) fetchOAuthToken(auth map[string]any) (string, error) { form := url.Values{ "grant_type": {"client_credentials"}, "client_id": {stringOf(auth[fieldClientID])}, - "client_secret": {stringOf(auth[apimCSecret])}, "resource": {stringOf(auth["audience"])}, + "resource": {stringOf(auth["audience"])}, + } + + if err = rs.setOAuthCredential(form, auth, endpoint, cert); err != nil { + return "", err } ctx, cancel := context.WithTimeout(rs.ctx, logicHTTPTimeout) @@ -58,7 +56,7 @@ func (rs *logicRunState) fetchOAuthToken(auth map[string]any) (string, error) { req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - resp, err := rs.p.http.Do(req) + resp, err := rs.p.http.Load().Do(req) if err != nil { return "", fmt.Errorf("%w: %w", errLogicTokenRequest, err) } @@ -81,3 +79,49 @@ func (rs *logicRunState) fetchOAuthToken(auth map[string]any) (string, error) { return orStr(tok.TokenType, "Bearer") + " " + tok.AccessToken, nil } + +// oauthCredential validates the block and reports whether it uses the Certificate credential type. +func oauthCredential(auth map[string]any) (bool, error) { + ct := stringOf(auth["credentialType"]) + cert := strings.EqualFold(ct, "Certificate") + + if ct != "" && !cert && !strings.EqualFold(ct, "Secret") { + return false, inputErr("the ActiveDirectoryOAuth credential type '%s' is not supported by this emulator", ct) + } + + required := []string{"tenant", "audience", fieldClientID, apimCSecret} + if cert { + required = []string{"tenant", "audience", fieldClientID, "pfx"} + } + + for _, k := range required { + if stringOf(auth[k]) == "" { + return false, inputErr("the ActiveDirectoryOAuth authentication requires '%s'", k) + } + } + + return cert, nil +} + +func (rs *logicRunState) setOAuthCredential(form url.Values, auth map[string]any, endpoint string, cert bool) error { + if !cert { + form.Set("client_secret", stringOf(auth[apimCSecret])) + + return nil + } + + pfx, err := loadLogicPFX(auth) + if err != nil { + return err + } + + assertion, err := pfx.clientAssertion(stringOf(auth[fieldClientID]), endpoint, rs.clock().UTC()) + if err != nil { + return err + } + + form.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") + form.Set("client_assertion", assertion) + + return nil +} diff --git a/services/azurearm/rp_logic_opers.go b/services/azurearm/rp_logic_opers.go new file mode 100644 index 0000000000..e32e86d054 --- /dev/null +++ b/services/azurearm/rp_logic_opers.go @@ -0,0 +1,54 @@ +package azurearm + +import ( + "strings" + "time" + + "github.com/google/uuid" +) + +const logicMaxOperations = 1000 + +// logicOperation is a run operation: the id the service hands out for an action taken on a run (a resubmit or a +// cancel), readable under workflows/{w}/runs/{r}/operations/{id}. +type logicOperation struct { + Created time.Time `json:"created"` + ID string `json:"id"` + Run string `json:"run"` + Kind string `json:"kind"` +} + +func (p *LogicProvider) recordOperationLocked(w *logicWorkflow, run, kind string) string { + op := &logicOperation{ID: uuid.NewString(), Run: run, Kind: kind, Created: p.clock.Now().UTC()} + w.Operations = append(w.Operations, op) + + if len(w.Operations) > logicMaxOperations { + w.Operations = w.Operations[len(w.Operations)-logicMaxOperations:] + } + + return op.ID +} + +func (w *logicWorkflow) operationLocation(base, run, op string) string { + return base + w.armID() + "/runs/" + run + "/operations/" + op + "?" + logicKAPIVersion + "=" + + logicAPIVersions()[0] +} + +func (h *Handler) logicGetOperation(q logicReq) error { + out, err := q.lp.read(q.ref, func(w *logicWorkflow) (any, error) { + r, ok := findRun(w, q.rest[1]) + if !ok { + return nil, ErrLogicRunNotFound + } + + for _, op := range w.Operations { + if op.Run == r.Name && strings.EqualFold(op.ID, q.rest[3]) { + return w.runBody(r, q.base), nil + } + } + + return nil, ErrLogicOperationMissing + }) + + return h.logicReply(q, out, err) +} diff --git a/services/azurearm/rp_logic_ops.go b/services/azurearm/rp_logic_ops.go index c38291f414..dd67032cd6 100644 --- a/services/azurearm/rp_logic_ops.go +++ b/services/azurearm/rp_logic_ops.go @@ -137,9 +137,9 @@ func (p *LogicProvider) callbackFor(r logicRef3, trigger, base string, body map[ } def := w.triggerDef(name) - if t := typeOf(def); t != logicTrigRequest && t != logicTrigManual { + if t := typeOf(def); t != logicTrigRequest && t != logicTrigManual && t != logicTrigWebhook { return nil, logicBadRequest("InvalidTriggerType", - "The trigger '%s' is not a request trigger and has no callback URL.", name) + "The trigger '%s' is not a request or webhook trigger and has no callback URL.", name) } if _, ok := w.Triggers[name]; !ok { diff --git a/services/azurearm/rp_logic_parsetime.go b/services/azurearm/rp_logic_parsetime.go index f43ce57f84..09da598250 100644 --- a/services/azurearm/rp_logic_parsetime.go +++ b/services/azurearm/rp_logic_parsetime.go @@ -1,6 +1,7 @@ package azurearm import ( + "slices" "strconv" "strings" "time" @@ -38,7 +39,7 @@ func tokenizeNetFormat(f string) []fmtTok { case 'y', 'M', 'd', 'H', 'h', 'm', 's', 'f', 'F', 't', 'K', 'z': toks = append(toks, fmtTok{kind: c, n: n}) default: - toks = append(toks, fmtTok{kind: 'L', lit: strings.Repeat(string(c), n)}) + toks = append(toks, fmtTok{kind: 'L', lit: strings.Repeat(string([]byte{c}), n)}) } i += n @@ -53,8 +54,8 @@ type parsedTime struct { } type timeScanner struct { - loc logicLocale s string + loc logicLocale pos int } @@ -73,19 +74,35 @@ func (sc *timeScanner) digits(minN, maxN int) (int, bool) { return v, err == nil } -// name matches one of names (full, or the first three letters when abbrev) ignoring case; it returns its index. -func (sc *timeScanner) name(names []string, abbrev bool) (int, bool) { - rest := strings.ToLower(sc.s[sc.pos:]) - best, bestLen := -1, 0 +// foldPrefix returns the byte length of the prefix of s that equals prefix ignoring case, or -1. It measures +// the original text: lower-casing can change a rune's byte length. +func foldPrefix(s, prefix string) int { + end, n := 0, utf8.RuneCountInString(prefix) - for i, nm := range names { - cand := strings.ToLower(nm) - if abbrev { - cand = string([]rune(cand)[:widthThree]) + for range n { + if end >= len(s) { + return -1 } - if strings.HasPrefix(rest, cand) && len(cand) > bestLen { - best, bestLen = i, len(cand) + _, w := utf8.DecodeRuneInString(s[end:]) + end += w + } + + if strings.EqualFold(s[:end], prefix) { + return end + } + + return -1 +} + +// name matches the longest of names at the cursor ignoring case; it returns its index. +func (sc *timeScanner) name(names []string) (int, bool) { + rest := sc.s[sc.pos:] + best, bestLen := -1, 0 + + for i, nm := range names { + if n := foldPrefix(rest, nm); n > bestLen { + best, bestLen = i, n } } @@ -155,7 +172,7 @@ func (sc *timeScanner) year(n int, pt *parsedTime) bool { func (sc *timeScanner) month(n int, pt *parsedTime) bool { if n >= widthThree { - i, ok := sc.name(sc.loc.months[:], n == widthThree) + i, ok := sc.name(sc.loc.monthNames(n == widthThree)) pt.month = i + 1 return ok @@ -169,7 +186,7 @@ func (sc *timeScanner) month(n int, pt *parsedTime) bool { func (sc *timeScanner) day(n int, pt *parsedTime) bool { if n >= widthThree { - _, ok := sc.name(sc.loc.days[:], n == widthThree) + _, ok := sc.name(sc.loc.dayNames(n == widthThree)) return ok } @@ -221,13 +238,22 @@ func (sc *timeScanner) fraction(t fmtTok, pt *parsedTime) bool { } func (sc *timeScanner) meridiem(pt *parsedTime) bool { - rest := strings.ToUpper(sc.s[sc.pos:]) + rest := sc.s[sc.pos:] + amLen, pmLen := -1, -1 + + if sc.loc.am != "" { + amLen = foldPrefix(rest, sc.loc.am) + } + + if sc.loc.pm != "" { + pmLen = foldPrefix(rest, sc.loc.pm) + } switch { - case strings.HasPrefix(rest, "AM"): - sc.pos += widthTwo - case strings.HasPrefix(rest, "PM"): - sc.pos += widthTwo + case amLen >= 0 && amLen >= pmLen: + sc.pos += amLen + case pmLen >= 0: + sc.pos += pmLen pt.pm = true default: return false @@ -336,7 +362,7 @@ func parseLocaleDefault(s string, loc logicLocale, key string) (logicTS, bool) { } } - for _, base := range logicLocaleFormats[key] { + for _, base := range append(slices.Clone(logicLocaleFormats[key]), loc.parse...) { for _, suf := range logicTimeSuffixes { if ts, ok := parseNetFormat(s, base+suf, loc); ok { return ts, true @@ -389,7 +415,7 @@ func parseWithFormat(s, format string, loc logicLocale) (logicTS, bool) { return ts, err == nil } - if f, std := logicStandardFormats[format]; std { + if f, std := loc.standardFormat(format); std { format = f } else if len(format) == 1 { return logicTS{}, false diff --git a/services/azurearm/rp_logic_poll.go b/services/azurearm/rp_logic_poll.go new file mode 100644 index 0000000000..bcafc380bd --- /dev/null +++ b/services/azurearm/rp_logic_poll.go @@ -0,0 +1,247 @@ +package azurearm + +import ( + "context" + "errors" + "net/http" + "strconv" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/blackbirdworks/gopherstack/pkgs/lockmetrics" +) + +const ( + logicTrigHTTP = logicSchemeHTTP + logicMaxRetryAfter = 24 * time.Hour +) + +func isPollingTrigger(typ string) bool { return typ == logicTrigRecurrence || typ == logicTrigHTTP } + +func validateLogicHTTPTrigger(name string, m map[string]any) error { + in, _ := objectOf(m["inputs"]) + + switch strings.ToUpper(stringOf(in["method"])) { + case http.MethodGet, http.MethodPut, http.MethodPost, http.MethodPatch, http.MethodDelete, http.MethodHead: + default: + return invalidTemplate("the trigger '%s' of type 'Http' requires a valid 'method' in its inputs", name) + } + + if stringOf(in["uri"]) == "" { + return invalidTemplate("the trigger '%s' of type 'Http' requires 'uri' in its inputs", name) + } + + return validateLogicRecurrence(name, m) +} + +type logicPollPlan struct { + def map[string]any + params map[string]any + wfDef map[string]any + pollURL string + wfName string +} + +func (p *LogicProvider) pollPlanLocked(wfKey, trigger string, scheduled time.Time, manual bool) (logicPollPlan, bool) { + w, ok := p.wf[wfKey] + if !ok { + return logicPollPlan{}, false + } + + ts, ok := w.Triggers[trigger] + if !ok || w.triggerType(trigger) != logicTrigHTTP { + return logicPollPlan{}, false + } + + if !manual && (ts.Next == nil || !ts.Next.Equal(scheduled)) { + return logicPollPlan{}, false + } + + return logicPollPlan{ + def: w.triggerDef(trigger), params: effectiveLogicParams(w), pollURL: ts.PollURL, wfName: w.Name, + wfDef: w.Definition, + }, true +} + +// pollState is a run state for the trigger's outbound call: it has its own lock so the call never holds the +// provider's. +func (p *LogicProvider) pollState(plan logicPollPlan, clock func() time.Time) *logicRunState { + scratch := &LogicProvider{mu: lockmetrics.New("azurearm.logicpoll"), clock: p.currentClock()} + scratch.http.Store(p.http.Load()) + + return &logicRunState{ + p: scratch, ctx: p.rootCtx, run: &logicRunRec{}, params: plan.params, vars: map[string]*logicVar{}, + def: plan.wfDef, clock: clock, wfName: plan.wfName, trigger: map[string]any{}, + } +} + +type logicPollResult struct { + err error + inputs map[string]any + resp *logicHTTPResponse + location string +} + +func (p *LogicProvider) pollOnce(plan logicPollPlan, trigger string) logicPollResult { + rs := p.pollState(plan, p.currentClock().Now) + env := &logicEnv{local: map[string]*logicActionRec{}} + + in, err := rs.evalInputs(env, trigger, plan.def) + if err != nil { + return logicPollResult{err: err} + } + + pol, err := parseRetryPolicy(in) + if err != nil { + return logicPollResult{err: err} + } + + req, err := rs.buildHTTPRequest(in, plan.def) + if err != nil { + return logicPollResult{err: err} + } + + req.async = false + + if plan.pollURL != "" { + req = followPollURL(req, plan.pollURL) + } + + resp, _, err := rs.doHTTP(req, pol, logicHTTPTimeout) + res := logicPollResult{err: err, inputs: httpInputs(in), resp: resp} + + if resp != nil { + res.location = asyncLocation(req.url, resp.headerValue("Location")) + } + + return res +} + +func (r *logicHTTPResponse) headerValue(name string) any { + for k, v := range r.headers { + if strings.EqualFold(k, name) { + return v + } + } + + return nil +} + +// followPollURL points req at the Location of the previous poll. Another origin gets a bare GET with only the +// workflow headers and no client certificate, so the credentials of the configured endpoint never leave it. +func followPollURL(req *logicHTTPRequest, next string) *logicHTTPRequest { + if sameOrigin(req.url, next) { + req.url = next + + return req + } + + return &logicHTTPRequest{ + method: http.MethodGet, url: next, header: pollHeaders(req, next), async: false, + } +} + +// retryAfter reads Retry-After as delay-seconds or an HTTP-date, clamped to logicMaxRetryAfter. +func retryAfter(r *logicHTTPResponse, now time.Time) time.Duration { + raw, _ := r.headerValue("Retry-After").(string) + raw = strings.TrimSpace(raw) + + if n, err := strconv.ParseInt(raw, 10, 64); err == nil { + if n < 0 { + return 0 + } + + return min(time.Duration(min(n, int64(logicMaxRetryAfter/time.Second)))*time.Second, logicMaxRetryAfter) + } + + at, err := http.ParseTime(raw) + if err != nil { + return 0 + } + + return min(max(at.Sub(now), 0), logicMaxRetryAfter) +} + +// firePoll runs one poll of an Http trigger outside the provider lock, then records its result under it. +func (p *LogicProvider) firePoll(wfKey, trigger string, scheduled time.Time, manual bool) { + p.mu.RLock("firePoll") + plan, ok := p.pollPlanLocked(wfKey, trigger, scheduled, manual) + p.mu.RUnlock() + + if !ok { + return + } + + res := p.pollOnce(plan, trigger) + + p.mu.Lock("firePollResult") + defer p.mu.Unlock() + + w, ok := p.wf[wfKey] + if !ok { + return + } + + ts, ok := w.Triggers[trigger] + if !ok || !manual && (ts.Next == nil || !ts.Next.Equal(scheduled)) || p.rootCtx.Err() != nil { + return + } + + next := p.applyPollResultLocked(w, ts, trigger, scheduled, res) + + if !manual { + p.armTriggerAtLocked(w, trigger, scheduled, next) + } +} + +// applyPollResultLocked records the poll and returns the earliest instant of the next one (zero: by recurrence). +func (p *LogicProvider) applyPollResultLocked( + w *logicWorkflow, ts *logicTriggerState, trigger string, scheduled time.Time, res logicPollResult, +) time.Time { + now := p.clock.Now().UTC() + f := logicFire{trigger: trigger, scheduled: scheduled, inputs: res.inputs, hasInputs: true} + + if res.err != nil { + p.recordPollFailure(w, f, now, res.err) + + return time.Time{} + } + + ts.PollURL = res.location + f.outputs = res.resp.outputs() + + if res.resp.status == http.StatusOK { + _, _ = p.startRunLocked(w, f) + + return time.Time{} + } + + p.recordSkippedTrigger(w, f, now, nil) + + if d := retryAfter(res.resp, now); d > 0 { + return now.Add(d) + } + + return time.Time{} +} + +func (p *LogicProvider) recordPollFailure(w *logicWorkflow, f logicFire, now time.Time, cause error) { + code := "TriggerRequestFailed" + if errors.Is(cause, context.DeadlineExceeded) { + code = "TriggerTimedOut" + } + + h := &logicHistory{ + Name: p.newRunName(now), Trigger: f.trigger, Start: now, End: now, Scheduled: f.scheduled, + Status: logicStFailed, Code: code, Tracking: uuid.NewString(), + Error: map[string]any{logicKCode: code, fieldMessage: cause.Error()}, + Inputs: logicContent{Value: f.inputs, Set: f.hasInputs}, + } + + hideTriggerContent(w.triggerDef(f.trigger), &h.Inputs, &h.Outputs) + + w.Histories = append(w.Histories, h) + trimLogicHistory(w) +} diff --git a/services/azurearm/rp_logic_repetitions.go b/services/azurearm/rp_logic_repetitions.go index 5f5d89e92f..bb5c870163 100644 --- a/services/azurearm/rp_logic_repetitions.go +++ b/services/azurearm/rp_logic_repetitions.go @@ -119,7 +119,7 @@ func (w *logicWorkflow) repetitionsOf(r *logicRunRec, action string, scope bool) } func (h *Handler) logicListRepetitions(q logicReq, scope bool) error { - return h.logicList(q, func(w *logicWorkflow, lq logicQuery) ([]map[string]any, error) { + return h.logicListPaged(q, func(w *logicWorkflow, lq logicQuery) ([]map[string]any, error) { r, ok := findRun(w, q.rest[1]) if !ok { return nil, ErrLogicRunNotFound @@ -140,7 +140,7 @@ func (h *Handler) logicListRepetitions(q logicReq, scope bool) error { } return out, nil - }) + }, false) } func (h *Handler) logicGetRepetition(q logicReq, scope bool) error { diff --git a/services/azurearm/rp_logic_reqhist.go b/services/azurearm/rp_logic_reqhist.go new file mode 100644 index 0000000000..b22d41182e --- /dev/null +++ b/services/azurearm/rp_logic_reqhist.go @@ -0,0 +1,290 @@ +package azurearm + +import ( + "context" + "strings" + "time" +) + +const ( + logicMaxRequests = 100 + logicMaxReqBodyStore = 256 << 10 + logicMaxRunBodyBytes = 4 << 20 + logicMaxRunRequests = 2000 + logicMaxRunTraces = 1000 + logicSegRequestHist = "requestHistories" + logicReqBodyKind = "ResponseBody" +) + +// logicRequestRec is one outbound HTTP call the engine made for an action (an attempt, retry or poll). +type logicRequestRec struct { + Start time.Time `json:"start"` + End time.Time `json:"end"` + Body any `json:"body,omitempty"` + ReqHeaders map[string]string `json:"reqHeaders,omitempty"` + RespHeaders map[string]string `json:"respHeaders,omitempty"` + Name string `json:"name"` + Method string `json:"method"` + URI string `json:"uri"` + BodySize int64 `json:"bodySize,omitempty"` + Status int `json:"status,omitempty"` + HasBody bool `json:"hasBody,omitempty"` + Responded bool `json:"responded,omitempty"` +} + +// logicRunBudget caps what one run keeps of its outbound calls and expression traces, so a loop of thousands of +// iterations cannot grow the run record without bound. Guarded by the provider lock. +type logicRunBudget struct { + bodyBytes int64 + requests int + traces int +} + +func (b *logicRunBudget) takeRequest() bool { + if b.requests >= logicMaxRunRequests { + return false + } + + b.requests++ + + return true +} + +func (b *logicRunBudget) takeBody(n int64) bool { + if b.bodyBytes+n > logicMaxRunBodyBytes { + return false + } + + b.bodyBytes += n + + return true +} + +func (b *logicRunBudget) takeTraces(n int) int { + n = min(n, max(logicMaxRunTraces-b.traces, 0)) + b.traces += n + + return n +} + +func secretHeader(k string) bool { + switch strings.ToLower(k) { + case "authorization", "proxy-authorization", "cookie", "set-cookie": + return true + } + + return false +} + +func redactHeaders(h map[string]string) { + for k := range h { + if secretHeader(k) { + delete(h, k) + } + } +} + +func (rs *logicRunState) currentRec(env *logicEnv, name string) *logicActionRec { + rs.p.mu.RLock("currentRec") + defer rs.p.mu.RUnlock() + + return env.local[name] +} + +// send performs one outbound call and records it on the action. +func (rs *logicRunState) send(ctx context.Context, req *logicHTTPRequest) (*logicHTTPResponse, error) { + start := rs.clock().UTC() + resp, err := rs.p.sendHTTP(ctx, req) + + if req.rec != nil { + rs.recordRequest(req, resp, start) + } + + return resp, err +} + +func (rs *logicRunState) recordRequest(req *logicHTTPRequest, resp *logicHTTPResponse, start time.Time) { + rq := &logicRequestRec{ + Start: start, End: rs.clock().UTC(), Method: req.method, URI: req.url, + ReqHeaders: map[string]string{}, + } + + for k, v := range req.header { + rq.ReqHeaders[k] = strings.Join(v, ", ") + } + + redactHeaders(rq.ReqHeaders) + + if resp != nil { + rq.Responded, rq.Status, rq.RespHeaders = true, resp.status, map[string]string{} + + for k, v := range resp.headers { + rq.RespHeaders[k] = logicString(v) + } + + redactHeaders(rq.RespHeaders) + + if resp.body != nil { + rq.BodySize = bodySize(resp.body) + } + } + + rs.p.mu.Lock("recordRequest") + defer rs.p.mu.Unlock() + + if len(req.rec.Requests) >= logicMaxRequests || !rs.budget.takeRequest() { + return + } + + if resp != nil && resp.body != nil && rq.BodySize <= logicMaxReqBodyStore && rs.budget.takeBody(rq.BodySize) { + rq.Body, rq.HasBody = resp.body, true + } + + rq.Name = rs.p.newVersionID(start) + req.rec.Requests = append(req.rec.Requests, rq) +} + +func bodySize(v any) int64 { + if s, ok := v.(string); ok { + return int64(len(s)) + } + + return marshalLogicSize(v) +} + +func (w *logicWorkflow) requestBody(a *logicActionRec, rq *logicRequestRec, rel, base string) map[string]any { + props := map[string]any{logicKStartTime: logicTime(rq.Start), logicKEndTime: logicTime(rq.End)} + + req := map[string]any{"method": rq.Method} + if !a.Inputs.Hidden { + req["uri"] = rq.URI + req[logicKHeaders] = orEmptyHeaders(rq.ReqHeaders) + } + + props["request"] = req + + if rq.Responded { + resp := map[string]any{logicKStatusCode: int64(rq.Status)} + + if !a.Outputs.Hidden { + resp[logicKHeaders] = orEmptyHeaders(rq.RespHeaders) + + if rq.HasBody { + resp["bodyLink"] = w.contentLink(base, "/workflows/"+w.FlowID+rel+"/requestHistories/"+rq.Name+ + "/contents/"+logicReqBodyKind, rq.Body) + } + } + + props["response"] = resp + } + + return map[string]any{ + logicFieldID: w.armID() + rel + "/requestHistories/" + rq.Name, + fieldName: rq.Name, fieldType: logicRunType + "/actions/" + logicSegRequestHist, fieldProperties: props, + } +} + +func orEmptyHeaders(h map[string]string) map[string]any { + out := make(map[string]any, len(h)) + for k, v := range h { + out[k] = v + } + + return out +} + +// requestTarget resolves the action record a request history route addresses: an action of the run, or one +// repetition of it when rep is set. +func (w *logicWorkflow) requestTarget(runName, action, rep string) (*logicActionRec, string, error) { + r, ok := findRun(w, runName) + if !ok { + return nil, "", ErrLogicRunNotFound + } + + scope := "/runs/" + r.Name + "/actions/" + action + + if rep == "" { + a, found := r.Actions[action] + if !found { + return nil, "", ErrLogicActionNotFound + } + + return a, scope, nil + } + + reps, err := w.repetitionsOf(r, action, false) + if err != nil { + return nil, "", err + } + + for _, x := range reps { + if x.Name == rep { + return &x.Rec, scope + "/repetitions/" + rep, nil + } + } + + return nil, "", ErrLogicRepNotFound +} + +func (h *Handler) logicListRequests(q logicReq, rep string) error { + return h.logicList(q, func(w *logicWorkflow, _ logicQuery) ([]map[string]any, error) { + a, rel, err := w.requestTarget(q.rest[1], q.rest[3], rep) + if err != nil { + return nil, err + } + + out := make([]map[string]any, 0, len(a.Requests)) + for _, rq := range a.Requests { + out = append(out, w.requestBody(a, rq, rel, q.base)) + } + + return out, nil + }) +} + +func (h *Handler) logicGetRequest(q logicReq, rep string) error { + name := q.rest[len(q.rest)-1] + + out, err := q.lp.read(q.ref, func(w *logicWorkflow) (any, error) { + a, rel, err := w.requestTarget(q.rest[1], q.rest[3], rep) + if err != nil { + return nil, err + } + + for _, rq := range a.Requests { + if strings.EqualFold(rq.Name, name) { + return w.requestBody(a, rq, rel, q.base), nil + } + } + + return nil, ErrLogicRequestNotFound + }) + + return h.logicReply(q, out, err) +} + +// requestContent resolves a request history body link; segs end in .../requestHistories/{name}/contents/{kind}. +func (w *logicWorkflow) requestContent(segs []string) (logicContent, bool) { + n := len(segs) + if segs[n-1] != logicReqBodyKind { + return logicContent{}, false + } + + rep := "" + if n == contentRequestRepSegs { + rep = segs[6] + } + + a, _, err := w.requestTarget(segs[2], segs[4], rep) + if err != nil || a.Outputs.Hidden { + return logicContent{}, false + } + + for _, rq := range a.Requests { + if rq.Name == segs[n-3] && rq.HasBody { + return logicContent{Value: rq.Body, Set: true}, true + } + } + + return logicContent{}, false +} diff --git a/services/azurearm/rp_logic_routes.go b/services/azurearm/rp_logic_routes.go index 5ef22e6dc9..8c8d2ef0bc 100644 --- a/services/azurearm/rp_logic_routes.go +++ b/services/azurearm/rp_logic_routes.go @@ -151,6 +151,10 @@ func (h *Handler) handleLogic(c *echo.Context, segs []string) error { path, _ := parseLogicPath(segs) q.ref, q.rest = path.ref, path.rest + if r.Method != http.MethodGet { + lp.noteBase(logicKey(q.ref.sub, q.ref.rg, q.ref.wf), q.base, h.Port) + } + if path.list != logicListNone { if r.Method != http.MethodGet { return h.writeError(c, http.StatusMethodNotAllowed, "MethodNotAllowed", "Method not allowed.") @@ -182,26 +186,44 @@ func logicHandlers() map[string]logicHandlerFunc { "POST:regenerateaccesskey": (*Handler).logicRegenerate, "POST:listcallbackurl": func(h *Handler, q logicReq) error { return h.logicCallback(q, "") }, "POST:validate": (*Handler).logicValidate, + "POST:listswagger": (*Handler).logicListSwagger, "GET:versions": (*Handler).logicListVersions, "GET:versions/*": (*Handler).logicGetVersion, "POST:versions/*/triggers/*/listcallbackurl": func(h *Handler, q logicReq) error { return h.logicCallback(q, q.rest[3]) }, - "GET:triggers": (*Handler).logicListTriggers, - "GET:triggers/*": (*Handler).logicGetTrigger, - "POST:triggers/*/listcallbackurl": func(h *Handler, q logicReq) error { return h.logicCallback(q, q.rest[1]) }, - "POST:triggers/*/run": (*Handler).logicRunTrigger, - "POST:triggers/*/reset": (*Handler).logicResetTrigger, - "POST:triggers/*/setstate": (*Handler).logicSetTriggerState, - "GET:triggers/*/schemas/*": (*Handler).logicTriggerSchema, - "GET:triggers/*/histories": (*Handler).logicListHistories, - "GET:triggers/*/histories/*": (*Handler).logicGetHistory, - "POST:triggers/*/histories/*/resubmit": (*Handler).logicResubmit, - "GET:runs": (*Handler).logicListRuns, - "GET:runs/*": (*Handler).logicGetRun, - "POST:runs/*/cancel": (*Handler).logicCancelRun, - "GET:runs/*/actions": (*Handler).logicListActions, - "GET:runs/*/actions/*": (*Handler).logicGetAction, + "GET:triggers": (*Handler).logicListTriggers, + "GET:triggers/*": (*Handler).logicGetTrigger, + "POST:triggers/*/listcallbackurl": func(h *Handler, q logicReq) error { + return h.logicCallback(q, q.rest[1]) + }, + "POST:triggers/*/run": (*Handler).logicRunTrigger, + "POST:triggers/*/reset": (*Handler).logicResetTrigger, + "POST:triggers/*/setstate": (*Handler).logicSetTriggerState, + "GET:triggers/*/schemas/*": (*Handler).logicTriggerSchema, + "GET:triggers/*/histories": (*Handler).logicListHistories, + "GET:triggers/*/histories/*": (*Handler).logicGetHistory, + "POST:triggers/*/histories/*/resubmit": (*Handler).logicResubmit, + "GET:runs": (*Handler).logicListRuns, + "GET:runs/*": (*Handler).logicGetRun, + "POST:runs/*/cancel": (*Handler).logicCancelRun, + "GET:runs/*/actions": (*Handler).logicListActions, + "GET:runs/*/actions/*": (*Handler).logicGetAction, + "GET:runs/*/operations/*": (*Handler).logicGetOperation, + "GET:runs/*/actions/*/requesthistories": func(h *Handler, q logicReq) error { return h.logicListRequests(q, "") }, + "GET:runs/*/actions/*/requesthistories/*": func(h *Handler, q logicReq) error { return h.logicGetRequest(q, "") }, + "POST:runs/*/actions/*/listexpressiontraces": func(h *Handler, q logicReq) error { + return h.logicExpressionTraces(q, "") + }, + "GET:runs/*/actions/*/repetitions/*/requesthistories": func(h *Handler, q logicReq) error { + return h.logicListRequests(q, q.rest[5]) + }, + "GET:runs/*/actions/*/repetitions/*/requesthistories/*": func(h *Handler, q logicReq) error { + return h.logicGetRequest(q, q.rest[5]) + }, + "POST:runs/*/actions/*/repetitions/*/listexpressiontraces": func(h *Handler, q logicReq) error { + return h.logicExpressionTraces(q, q.rest[5]) + }, "GET:runs/*/actions/*/repetitions": func(h *Handler, q logicReq) error { return h.logicListRepetitions(q, false) }, @@ -407,6 +429,14 @@ func (h *Handler) logicListWorkflows(q logicReq, kind logicListKind) error { } func (h *Handler) logicList(q logicReq, items func(w *logicWorkflow, lq logicQuery) ([]map[string]any, error)) error { + return h.logicListPaged(q, items, true) +} + +// logicListPaged answers a list; the repetitions lists are unpaged in the armlogic SDK (no nextLink), so they +// return every item. +func (h *Handler) logicListPaged( + q logicReq, items func(w *logicWorkflow, lq logicQuery) ([]map[string]any, error), paged bool, +) error { lq, err := h.logicQuery(q) if err != nil { return h.writeAPIError(q.c, err) @@ -418,6 +448,10 @@ func (h *Handler) logicList(q logicReq, items func(w *logicWorkflow, lq logicQue return nil, ierr } + if !paged { + return pageOf{Data: all}, nil + } + return pageLogic(all, lq), nil }) if err != nil { diff --git a/services/azurearm/rp_logic_routes_children.go b/services/azurearm/rp_logic_routes_children.go index cc5b129be4..64749ff8dc 100644 --- a/services/azurearm/rp_logic_routes_children.go +++ b/services/azurearm/rp_logic_routes_children.go @@ -93,7 +93,40 @@ func (h *Handler) logicTriggerWrite(q logicReq, f func(w *logicWorkflow, name st } func (h *Handler) logicRunTrigger(q logicReq) error { - return h.logicTriggerWrite(q, q.lp.runTriggerLocked) + var wfKey, poll string + + _, err := q.lp.write(q.ref, func(w *logicWorkflow) (any, error) { + name, ok := matchTriggerName(w, q.rest[1]) + if !ok { + return nil, ErrLogicTriggerNotFound + } + + if w.triggerType(name) != logicTrigHTTP { + return nil, q.lp.runTriggerLocked(w, name) + } + + if w.State != logicStateEnabled || w.Triggers[name].State != logicStateEnabled { + return nil, logicBadRequest( + "WorkflowDisabled", + "The workflow '%s' or trigger '%s' is disabled.", + w.Name, + name, + ) + } + + wfKey, poll = w.key(), name + + return nil, nil //nolint:nilnil // void result + }) + if err != nil { + return h.writeAPIError(q.c, err) + } + + if poll != "" { + q.lp.firePoll(wfKey, poll, q.lp.currentClock().Now().UTC(), true) + } + + return q.c.NoContent(http.StatusOK) } func (h *Handler) logicResetTrigger(q logicReq) error { @@ -199,11 +232,26 @@ func (h *Handler) logicGetRun(q logicReq) error { } func (h *Handler) logicCancelRun(q logicReq) error { - live, err := q.lp.write(q.ref, func(w *logicWorkflow) (any, error) { return q.lp.cancelRunLocked(w, q.rest[1]) }) + var location string + + live, err := q.lp.write(q.ref, func(w *logicWorkflow) (any, error) { + l, cerr := q.lp.cancelRunLocked(w, q.rest[1]) + if cerr != nil { + return nil, cerr + } + + if r, ok := findRun(w, q.rest[1]); ok { + location = w.operationLocation(q.base, r.Name, q.lp.recordOperationLocked(w, r.Name, "Cancel")) + } + + return l, nil + }) if err != nil { return h.writeAPIError(q.c, err) } + q.c.Response().Header().Set("Location", location) + if l, ok := live.(*logicLive); ok && l != nil { logicCancelRun(l) } @@ -259,6 +307,8 @@ func (h *Handler) logicGetAction(q logicReq) error { // logicResubmit starts a new run from a trigger history entry's recorded inputs and outputs // (armlogic v1.2.0 WorkflowTriggerHistoriesClient.Resubmit answers 202). func (h *Handler) logicResubmit(q logicReq) error { + var location string + _, err := q.lp.write(q.ref, func(w *logicWorkflow) (any, error) { name, ok := matchTriggerName(w, q.rest[1]) if !ok { @@ -274,12 +324,21 @@ func (h *Handler) logicResubmit(q logicReq) error { return nil, logicBadRequest("InvalidRequest", "The trigger history '%s' did not fire a run.", hist.Name) } - _, err := q.lp.startRunLocked(w, logicFire{ + started, err := q.lp.startRunLocked(w, logicFire{ trigger: name, scheduled: q.lp.clock.Now().UTC(), outputs: hist.Outputs.Value, inputs: hist.Inputs.Value, hasInputs: hist.Inputs.Set, }) + if err != nil { + return nil, err + } + + location = w.operationLocation( + q.base, + started.runName, + q.lp.recordOperationLocked(w, started.runName, "Resubmit"), + ) - return nil, err + return nil, nil //nolint:nilnil // void result } return nil, ErrLogicHistoryNotFound @@ -288,5 +347,7 @@ func (h *Handler) logicResubmit(q logicReq) error { return h.writeAPIError(q.c, err) } + q.c.Response().Header().Set("Location", location) + return q.c.NoContent(http.StatusAccepted) } diff --git a/services/azurearm/rp_logic_run.go b/services/azurearm/rp_logic_run.go index b78f4c0e98..9e01103b39 100644 --- a/services/azurearm/rp_logic_run.go +++ b/services/azurearm/rp_logic_run.go @@ -239,14 +239,22 @@ func (p *LogicProvider) fireRecurrence(wfKey, trigger string, scheduled time.Tim return } + if w.triggerType(trigger) == logicTrigHTTP { + p.wg.Go(func() { p.firePoll(wfKey, trigger, scheduled, false) }) + + return + } + _, _ = p.startRunLocked(w, logicFire{trigger: trigger, scheduled: scheduled, outputs: map[string]any{}}) p.armTriggerLocked(w, trigger, scheduled) } func (p *LogicProvider) armWorkflowLocked(w *logicWorkflow) { + p.syncWebhooksLocked(w) + defs, _ := objectOf(w.Definition[logicSegTriggers]) for name, t := range defs { - if typeOf(t) == logicTrigRecurrence { + if isPollingTrigger(typeOf(t)) { p.armTriggerLocked(w, name, p.clock.Now().Add(-time.Nanosecond)) } } @@ -254,6 +262,11 @@ func (p *LogicProvider) armWorkflowLocked(w *logicWorkflow) { // armTriggerLocked schedules the first occurrence strictly after the given instant. func (p *LogicProvider) armTriggerLocked(w *logicWorkflow, name string, after time.Time) { + p.armTriggerAtLocked(w, name, after, time.Time{}) +} + +// armTriggerAtLocked is armTriggerLocked with a floor: the next occurrence is not earlier than notBefore. +func (p *LogicProvider) armTriggerAtLocked(w *logicWorkflow, name string, after, notBefore time.Time) { key := w.key() + "|" + name if old, ok := p.timers[key]; ok { @@ -276,6 +289,12 @@ func (p *LogicProvider) armTriggerLocked(w *logicWorkflow, name string, after ti return } + if next.Before(notBefore) { + if r := parseLogicRecurrence(def, ts.Anchor); r.end.IsZero() || !notBefore.After(r.end) { + next = notBefore + } + } + ts.Next = &next wfKey := w.key() @@ -284,7 +303,7 @@ func (p *LogicProvider) armTriggerLocked(w *logicWorkflow, name string, after ti // ResetTrigger re-anchors a recurrence trigger at the current time. func (p *LogicProvider) resetTriggerLocked(w *logicWorkflow, name string) error { - if w.triggerType(name) != logicTrigRecurrence { + if !isPollingTrigger(w.triggerType(name)) { return logicBadRequest( "InvalidTriggerType", "The trigger '%s' is not a polling or recurrence trigger and cannot be reset.", @@ -293,7 +312,7 @@ func (p *LogicProvider) resetTriggerLocked(w *logicWorkflow, name string) error } ts := w.Triggers[name] - ts.Anchor, ts.Last = p.clock.Now().UTC(), nil + ts.Anchor, ts.Last, ts.PollURL = p.clock.Now().UTC(), nil, "" p.armTriggerLocked(w, name, p.clock.Now().Add(-time.Nanosecond)) return nil diff --git a/services/azurearm/rp_logic_swagger.go b/services/azurearm/rp_logic_swagger.go new file mode 100644 index 0000000000..b633ca5cde --- /dev/null +++ b/services/azurearm/rp_logic_swagger.go @@ -0,0 +1,94 @@ +package azurearm + +import ( + "net/http" + "net/url" + "strings" +) + +const ( + logicSwaggerVersion = "2.0" + logicKSchema = "schema" +) + +// swaggerDocument builds a Swagger 2.0 description of the workflow's Request triggers: one operation per trigger +// (method, relativePath, JSON body schema) on the emulator's invoke path, with the callback signature parameters. +func (w *logicWorkflow) swaggerDocument(base string) map[string]any { + host, scheme := "", logicSchemeHTTPS + + if u, err := url.Parse(base); err == nil && u.Host != "" { + host, scheme = u.Host, u.Scheme + } + + paths := map[string]any{} + + for _, name := range sortedTriggerNames(w) { + typ := w.triggerType(name) + if typ != logicTrigRequest && typ != logicTrigManual { + continue + } + + path, method, op := w.swaggerOperation(name) + + item, _ := paths[path].(map[string]any) + if item == nil { + item = map[string]any{} + paths[path] = item + } + + item[method] = op + } + + return map[string]any{ + "swagger": logicSwaggerVersion, + "info": map[string]any{"title": w.Name, logicKVersion: w.Version}, + logicKHost: host, + "basePath": strings.TrimSuffix(logicDataPrefix, "/") + "/" + w.FlowID, + "schemes": []any{scheme}, + "paths": paths, + } +} + +func (w *logicWorkflow) swaggerOperation(trigger string) (string, string, map[string]any) { + in, _ := objectOf(w.triggerDef(trigger)["inputs"]) + + method := strings.ToLower(stringOf(in["method"])) + if method == "" { + method = strings.ToLower(http.MethodPost) + } + + path := "/triggers/" + trigger + "/paths/invoke" + params := []any{} + + if rel := stringOf(in["relativePath"]); rel != "" { + path += "/" + strings.TrimPrefix(rel, "/") + + for _, p := range relativePathParams(rel) { + params = append(params, map[string]any{ + fieldName: p, "in": logicKPath, "required": true, fieldType: "string", + }) + } + } + + for _, q := range []string{logicKAPIVersion, "sp", "sv", logicKSig} { + params = append(params, map[string]any{fieldName: q, "in": logicKQuery, "required": true, fieldType: "string"}) + } + + if schema, ok := objectOf(in[logicKSchema]); ok && method != "get" && method != logicKDelete { + params = append(params, map[string]any{fieldName: logicKBody, "in": logicKBody, logicKSchema: schema}) + } + + return path, method, map[string]any{ + "operationId": trigger, + logicKParameters: params, + "responses": map[string]any{ + logicKDefault: map[string]any{logicKDescription: "The response of the workflow run."}, + }, + } +} + +func (h *Handler) logicListSwagger(q logicReq) error { + out, err := q.lp.read(q.ref, func(w *logicWorkflow) (any, error) { return w.swaggerDocument(q.base), nil }) + + return h.logicReply(q, out, err) +} diff --git a/services/azurearm/rp_logic_time.go b/services/azurearm/rp_logic_time.go index f9e4dfa432..69546338ce 100644 --- a/services/azurearm/rp_logic_time.go +++ b/services/azurearm/rp_logic_time.go @@ -9,6 +9,7 @@ import ( const ( logicLocaleEnUS = "en-us" logicRoundTrip = "o" + logicRFC1123 = "ddd, dd MMM yyyy HH:mm:ss 'GMT'" widthTwo = 2 widthThree = 3 widthFour = 4 @@ -45,33 +46,41 @@ var logicStandardFormats = map[string]string{ //nolint:gochecknoglobals // stati } type logicLocale struct { - months [12]string - days [7]string + std map[string]string + months [12]string + abbrMonths [12]string + days [7]string + abbrDays [7]string + am string + pm string + parse []string } -//nolint:gochecknoglobals // static locale name tables -var logicLocales = map[string]logicLocale{ - logicLocaleEnUS: { - months: [12]string{ - "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", - "November", "December", - }, - days: [7]string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}, - }, - "fr-fr": { - months: [12]string{ - "janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", - "novembre", "décembre", - }, - days: [7]string{"dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"}, - }, - "es-es": { - months: [12]string{ - "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", - "noviembre", "diciembre", - }, - days: [7]string{"domingo", "lunes", "martes", "miércoles", "jueves", "viernes", "sábado"}, - }, +func (l logicLocale) monthNames(abbr bool) []string { + if abbr { + return l.abbrMonths[:] + } + + return l.months[:] +} + +func (l logicLocale) dayNames(abbr bool) []string { + if abbr { + return l.abbrDays[:] + } + + return l.days[:] +} + +// standardFormat returns the custom pattern of a .NET standard specifier for the culture. +func (l logicLocale) standardFormat(spec string) (string, bool) { + if f, ok := l.std[spec]; ok { + return f, true + } + + f, ok := logicStandardFormats[spec] + + return f, ok } // formatLogicTime renders ts using a .NET standard or custom format string. @@ -94,7 +103,11 @@ func formatLogicTime(ts logicTS, format, locale string) (string, error) { return out, nil } - if f, std := logicStandardFormats[format]; std { + if format == "R" || format == "r" { + return formatLogicCustom(ts.t, logicRFC1123, logicLocales[logicLocaleEnUS]), nil + } + + if f, std := loc.standardFormat(format); std { format = f } else if len(format) == 1 { return "", exprErr("the format specifier %q is not valid", format) @@ -175,12 +188,12 @@ func formatField(t time.Time, c byte, n int, loc logicLocale) string { case 'f', 'F': return fmtFraction(t, n, c == 'F') case 't': - return fmtMeridiem(t, n) + return fmtMeridiem(t, n, loc) case 'K', 'Z': return "Z" } - return strings.Repeat(string(c), n) + return strings.Repeat(string([]byte{c}), n) } func padNum(v, width int) string { @@ -204,22 +217,16 @@ func fmtYear(y, n int) string { } func fmtMonth(t time.Time, n int, loc logicLocale) string { - switch { - case n >= widthFour: - return loc.months[t.Month()-1] - case n == widthThree: - return string([]rune(loc.months[t.Month()-1])[:widthThree]) + if n >= widthThree { + return loc.monthNames(n == widthThree)[t.Month()-1] } return padNum(int(t.Month()), n) } func fmtDay(t time.Time, n int, loc logicLocale) string { - switch { - case n >= widthFour: - return loc.days[t.Weekday()] - case n == widthThree: - return string([]rune(loc.days[t.Weekday()])[:widthThree]) + if n >= widthThree { + return loc.dayNames(n == widthThree)[t.Weekday()] } return padNum(t.Day(), n) @@ -240,14 +247,14 @@ func fmtFraction(t time.Time, n int, trim bool) string { return out } -func fmtMeridiem(t time.Time, n int) string { - s := "AM" +func fmtMeridiem(t time.Time, n int, loc logicLocale) string { + s := loc.am if t.Hour() >= twelve { - s = "PM" + s = loc.pm } if n == 1 { - return s[:1] + return string([]rune(s)[:min(1, len([]rune(s)))]) } return s diff --git a/services/azurearm/rp_logic_trace.go b/services/azurearm/rp_logic_trace.go new file mode 100644 index 0000000000..5e43847964 --- /dev/null +++ b/services/azurearm/rp_logic_trace.go @@ -0,0 +1,308 @@ +package azurearm + +import ( + "regexp" + "slices" + "strconv" + "strings" +) + +const ( + logicKText = "text" + logicMaxTraces = 100 + logicMaxTraceNodes = 200 + logicMaxTraceDepth = 8 + logicMaxTraceValue = 16 << 10 +) + +// logicTraceNode is one evaluated expression, with the sub-expressions it evaluated. +type logicTraceNode struct { + Value any `json:"value,omitempty"` + Text string `json:"text"` + Err string `json:"err,omitempty"` + Subs []*logicTraceNode `json:"subs,omitempty"` + HasValue bool `json:"hasValue,omitempty"` +} + +// logicTraceRoot is a template string found in an action's inputs and its evaluation. +type logicTraceRoot struct { + Path string `json:"path"` + Node logicTraceNode `json:"node"` +} + +type logicTracer struct { + roots []*logicTraceRoot + stack [][]*logicTraceNode + path []string + nodes int +} + +func newLogicTracer(root string) *logicTracer { return &logicTracer{path: []string{root}} } + +func (t *logicTracer) active() bool { + return len(t.stack) > 0 && len(t.stack) <= logicMaxTraceDepth && t.nodes < logicMaxTraceNodes +} + +func (t *logicTracer) pathString() string { + var b strings.Builder + + for i, s := range t.path { + if i > 0 && !strings.HasPrefix(s, "[") { + b.WriteByte('.') + } + + b.WriteString(s) + } + + return b.String() +} + +func (t *logicTracer) wrap(n *logicExpr, f func() (any, error)) (any, error) { + t.stack = append(t.stack, nil) + t.nodes++ + + v, err := f() + top := len(t.stack) - 1 + node := &logicTraceNode{Text: n.text(), Subs: t.stack[top]} + t.stack = t.stack[:top] + setTraceResult(node, v, err) + + t.stack[top-1] = append(t.stack[top-1], node) + + return v, err +} + +func setTraceResult(n *logicTraceNode, v any, err error) { + if err != nil { + n.Err = strings.TrimPrefix(err.Error(), "logic expression error: ") + + return + } + + if bodySize(v) <= logicMaxTraceValue { + n.Value, n.HasValue = v, true + } +} + +func (t *logicTracer) beginRoot() { t.stack = append(t.stack, nil) } + +func (t *logicTracer) endRoot(text string, v any, err error) { + top := len(t.stack) - 1 + subs := t.stack[top] + t.stack = t.stack[:top] + + if len(subs) == 0 && err == nil { + return + } + + if len(t.roots) >= logicMaxTraces { + return + } + + if len(subs) == 1 && strings.HasPrefix(text, "@") && !strings.HasPrefix(text, "@{") { + subs = subs[0].Subs + } + + root := &logicTraceRoot{Path: t.pathString(), Node: logicTraceNode{Text: text, Subs: subs}} + setTraceResult(&root.Node, v, err) + t.roots = append(t.roots, root) +} + +func (n *logicExpr) text() string { + switch n.kind { + case exprLit: + switch v := n.lit.(type) { + case nil: + return logicKNull + case string: + return "'" + strings.ReplaceAll(v, "'", "''") + "'" + } + + return logicString(n.lit) + case exprCall: + args := make([]string, len(n.args)) + for i, a := range n.args { + args[i] = a.text() + } + + return n.name + "(" + strings.Join(args, ",") + ")" + case exprIndex: + return n.base.text() + safeMark(n.safe) + "[" + n.idx.text() + "]" + case exprProp: + return n.base.text() + safeMark(n.safe) + "." + n.name + } + + return "" +} + +func safeMark(safe bool) string { + if safe { + return "?" + } + + return "" +} + +func (c *logicEvalCtx) eval(n *logicExpr) (any, error) { + if c.trace == nil || !c.trace.active() { + return c.evalNode(n) + } + + return c.trace.wrap(n, func() (any, error) { return c.evalNode(n) }) +} + +func (c *logicEvalCtx) pushPath(seg string) { + if c.trace != nil { + c.trace.path = append(c.trace.path, seg) + } +} + +func (c *logicEvalCtx) popPath() { + if c.trace != nil { + c.trace.path = c.trace.path[:len(c.trace.path)-1] + } +} + +func indexSeg(i int) string { return "[" + strconv.Itoa(i) + "]" } + +// evalTraced evaluates v and records the expressions evaluated under root on the named action. +func (rs *logicRunState) evalTraced(env *logicEnv, name, root string, v any) (any, error) { + c := rs.evalCtx(env) + c.trace = newLogicTracer(root) + + out, err := evalLogicValue(v, c) + + if len(c.trace.roots) == 0 { + return out, err + } + + secure := secureParamPattern(rs.def) + + for _, r := range c.trace.roots { + if secretTracePath(r.Path) { + stripTraceValues(&r.Node) + } else if secure != nil { + maskSecureTrace(&r.Node, secure) + } + } + + rs.p.mu.Lock("storeTraces") + defer rs.p.mu.Unlock() + + if rec := env.local[name]; rec != nil { + room := max(logicMaxTraces-len(rec.Traces), 0) + n := rs.budget.takeTraces(min(room, len(c.trace.roots))) + rec.Traces = append(rec.Traces, c.trace.roots[:n]...) + } + + return out, err +} + +func traceBody(n *logicTraceNode, hideValues bool) map[string]any { + out := map[string]any{logicKText: n.Text} + + if !hideValues && n.HasValue { + out["value"] = n.Value + } + + if n.Err != "" { + out[logicKError] = map[string]any{logicKCode: logicCodeInvalidTmpl, fieldMessage: n.Err} + } + + if len(n.Subs) > 0 { + subs := make([]any, len(n.Subs)) + for i, s := range n.Subs { + subs[i] = traceBody(s, hideValues) + } + + out["subexpressions"] = subs + } + + return out +} + +func expressionTraces(a *logicActionRec) map[string]any { + inputs := make([]any, 0, len(a.Traces)) + + for _, r := range a.Traces { + b := traceBody(&r.Node, a.Inputs.Hidden) + b["path"] = r.Path + inputs = append(inputs, b) + } + + return map[string]any{"inputs": inputs} +} + +func (h *Handler) logicExpressionTraces(q logicReq, rep string) error { + out, err := q.lp.read(q.ref, func(w *logicWorkflow) (any, error) { + a, _, terr := w.requestTarget(q.rest[1], q.rest[3], rep) + if terr != nil { + return nil, terr + } + + return expressionTraces(a), nil + }) + + return h.logicReply(q, out, err) +} + +// secretTracePath reports whether the expressions at path feed a credential: the authentication block or an +// Authorization or Cookie header. +func secretTracePath(path string) bool { + lp := strings.ToLower(path) + + for _, pre := range []string{ + "inputs.authentication", "inputs.cookie", "inputs.headers.authorization", + "inputs.headers.proxy-authorization", "inputs.headers.cookie", + } { + if strings.HasPrefix(lp, pre) { + return true + } + } + + return false +} + +// secureParamPattern matches a parameters('name') reference to a secureString or secureObject parameter of the +// definition; nil when it declares none. +func secureParamPattern(def map[string]any) *regexp.Regexp { + defs, _ := objectOf(def["parameters"]) + + var names []string + + for name, d := range defs { + dm, _ := objectOf(d) + if typ := strings.ToLower(stringOf(dm[fieldType])); typ == "securestring" || typ == "secureobject" { + names = append(names, regexp.QuoteMeta(name)) + } + } + + if len(names) == 0 { + return nil + } + + slices.Sort(names) + + return regexp.MustCompile(`(?i)\bparameters\(\s*'(?:` + strings.Join(names, "|") + `)'\s*\)`) +} + +// maskSecureTrace drops the value of every expression that reads a secure parameter, and so of the ones around it. +func maskSecureTrace(n *logicTraceNode, secure *regexp.Regexp) { + if secure.MatchString(n.Text) { + stripTraceValues(n) + + return + } + + for _, s := range n.Subs { + maskSecureTrace(s, secure) + } +} + +func stripTraceValues(n *logicTraceNode) { + n.Value, n.HasValue = nil, false + + for _, s := range n.Subs { + stripTraceValues(s) + } +} diff --git a/services/azurearm/rp_logic_trigger.go b/services/azurearm/rp_logic_trigger.go index 233a805e44..6aa6283aad 100644 --- a/services/azurearm/rp_logic_trigger.go +++ b/services/azurearm/rp_logic_trigger.go @@ -28,6 +28,7 @@ const ( contentTriggerSegs = 5 contentDeepSegs = 7 contentRepSegs = 9 + contentRequestRepSegs = 11 ) func validCallbackKeyType(k string) bool { @@ -252,7 +253,8 @@ func (p *LogicProvider) resolveInvoke( } def := w.triggerDef(trigger) - if _, has := w.Triggers[trigger]; !has || typeOf(def) != logicTrigRequest && typeOf(def) != logicTrigManual { + if _, has := w.Triggers[trigger]; !has || typeOf(def) != logicTrigRequest && typeOf(def) != logicTrigManual && + typeOf(def) != logicTrigWebhook { writeLogicData(rw, http.StatusNotFound, "TriggerNotFound", "The trigger '"+trigger+"' was not found.") return logicInvokeTarget{}, false @@ -514,18 +516,37 @@ func contentPath(flow string, segs []string) string { // lookupContent resolves a content path to its stored value; caller holds p.mu. func (w *logicWorkflow) lookupContent(segs []string) (logicContent, bool) { + switch segs[1] { + case logicSegRuns: + return w.lookupRunContent(segs) + case logicSegTriggers: + if len(segs) == contentDeepSegs { + return w.historyContent(segs[2], segs[4], segs[len(segs)-1]) + } + } + + return logicContent{}, false +} + +func (w *logicWorkflow) lookupRunContent(segs []string) (logicContent, bool) { kind := segs[len(segs)-1] - switch { - case segs[1] == logicSegRuns && len(segs) == contentTriggerSegs: + if len(segs) == contentTriggerSegs { return w.runTriggerContent(segs[2], kind) - case segs[1] == logicSegRuns && len(segs) == contentDeepSegs && segs[3] == logicKActions: + } + + if len(segs) < contentDeepSegs || segs[3] != logicKActions { + return logicContent{}, false + } + + switch { + case len(segs) == contentDeepSegs: return w.actionContent(segs[2], segs[4], kind) - case segs[1] == logicSegRuns && len(segs) == contentRepSegs && segs[3] == logicKActions && - segs[5] == logicSegRepetitions: + case len(segs) == contentRepSegs && segs[5] == logicSegRepetitions: return w.repetitionContent(segs[2], segs[4], segs[6], kind) - case segs[1] == logicSegTriggers && len(segs) == contentDeepSegs: - return w.historyContent(segs[2], segs[4], kind) + case len(segs) == contentRepSegs && segs[5] == logicSegRequestHist, + len(segs) == contentRequestRepSegs && segs[5] == logicSegRepetitions && segs[7] == logicSegRequestHist: + return w.requestContent(segs) } return logicContent{}, false diff --git a/services/azurearm/rp_logic_wffuncs.go b/services/azurearm/rp_logic_wffuncs.go index d26c9e499b..e0e1f046c6 100644 --- a/services/azurearm/rp_logic_wffuncs.go +++ b/services/azurearm/rp_logic_wffuncs.go @@ -118,9 +118,9 @@ func workflowFuncs() map[string]wfFunc { return out[logicKBody], nil }}, - "trigger": {n: 0, f: func(c *logicEvalCtx, _ []any) (any, error) { return c.rs.trigger, nil }}, - "variables": {n: 1, f: wfVariables}, - "parameters": {n: 1, f: wfParameters}, + "trigger": {n: 0, f: func(c *logicEvalCtx, _ []any) (any, error) { return c.rs.trigger, nil }}, + "variables": {n: 1, f: wfVariables}, + logicKParameters: {n: 1, f: wfParameters}, "items": {n: 1, f: func(c *logicEvalCtx, a []any) (any, error) { f, ok := c.frame(logicString(a[0])) if !ok { @@ -311,6 +311,10 @@ func wfIterationIndexes(c *logicEvalCtx, a []any) (any, error) { } func wfListCallbackURL(c *logicEvalCtx, _ []any) (any, error) { + if c.rs.callbackURL != "" { + return c.rs.callbackURL, nil + } + return nil, exprErr( "listCallbackUrl() is only valid in HttpWebhook and ApiConnectionWebhook triggers and actions, "+ "and workflow '%s' is not evaluating one", c.rs.wfName, diff --git a/services/azurearm/rp_logic_xml.go b/services/azurearm/rp_logic_xml.go index a0e417ec8f..c62c0aba96 100644 --- a/services/azurearm/rp_logic_xml.go +++ b/services/azurearm/rp_logic_xml.go @@ -369,7 +369,7 @@ func logicXML(a []any) (any, error) { func logicTypeName(v any) string { switch v.(type) { case nil: - return "null" + return logicKNull case []any: return "an array" case bool: diff --git a/services/dynamodb/handler.go b/services/dynamodb/handler.go index 1ac9fd642d..4fc1d2565a 100644 --- a/services/dynamodb/handler.go +++ b/services/dynamodb/handler.go @@ -181,6 +181,14 @@ func (h *DynamoDBHandler) StartWorker(ctx context.Context) error { return nil } +// DrainDeletedTables synchronously finalises every table queued for deletion, +// waiting out any janitor pass already in flight. +func (h *DynamoDBHandler) DrainDeletedTables(ctx context.Context) { + if h.janitor != nil { + h.janitor.runTableCleaner(ctx) + } +} + // Shutdown stops the janitor worker and waits for it to exit (or until ctx expires). func (h *DynamoDBHandler) Shutdown(ctx context.Context) { h.janitorMu.Lock() diff --git a/services/dynamodb/janitor.go b/services/dynamodb/janitor.go index 45ff7a0558..7caefeab67 100644 --- a/services/dynamodb/janitor.go +++ b/services/dynamodb/janitor.go @@ -187,6 +187,9 @@ func (j *Janitor) SweepOnce(ctx context.Context) { func (j *Janitor) runTableCleaner(ctx context.Context) { db := j.Backend + db.cleanMu.Lock("DDBTableCleaner") + defer db.cleanMu.Unlock() + // Snapshot the tables to clean up and remove them from deletingTables under the // global lock. The slow work (timer cancellation, mutex close) is done outside the // lock so that concurrent DescribeTable / PutItem / Query calls are not stalled @@ -202,6 +205,10 @@ func (j *Janitor) runTableCleaner(ctx context.Context) { table.mu.Close() } + if len(tablesToClose) > 0 { + db.pruneDeadCapacityCounters() + } + telemetry.RecordWorkerQueueDepth("dynamodb", "TableCleaner", depth) telemetry.RecordWorkerTask("dynamodb", "TableCleaner", "success") telemetry.RecordWorkerItems("dynamodb", "TableCleaner", depth) diff --git a/services/dynamodb/metering.go b/services/dynamodb/metering.go index 02519d2bf2..93326ce3c9 100644 --- a/services/dynamodb/metering.go +++ b/services/dynamodb/metering.go @@ -96,6 +96,27 @@ func (db *InMemoryDB) pruneCapacityCounters(dead []capacityKey) { db.meterCounters.Store(&next) } +// pruneDeadCapacityCounters drops counters whose table no longer exists, so +// deleted tables do not wait for the next usage collection to be released. +func (db *InMemoryDB) pruneDeadCapacityCounters() { + m := db.meterCounters.Load() + if m == nil { + return + } + + var dead []capacityKey + + for k := range *m { + if db.getTableInRegionRLocked(k.region, k.table, "pruneDeadCapacityCounters") == nil { + dead = append(dead, k) + } + } + + if len(dead) > 0 { + db.pruneCapacityCounters(dead) + } +} + // DrainCapacityUsage returns and clears the request units consumed by on-demand tables. func (db *InMemoryDB) DrainCapacityUsage() []CapacityUsage { m := db.meterCounters.Load() diff --git a/services/dynamodb/metering_prune_internal_test.go b/services/dynamodb/metering_prune_internal_test.go new file mode 100644 index 0000000000..9b001b45f6 --- /dev/null +++ b/services/dynamodb/metering_prune_internal_test.go @@ -0,0 +1,60 @@ +package dynamodb + +import ( + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + ddbsdk "github.com/aws/aws-sdk-go-v2/service/dynamodb" + "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestTableCleanerPrunesCapacityCounters(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + deleted bool + wantTables int + }{ + {name: "deleted table counter released", deleted: true, wantTables: 0}, + {name: "live table counter kept", deleted: false, wantTables: 1}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + db := NewInMemoryDB() + db.EnableCapacityMetering() + + _, err := db.CreateTable(t.Context(), &ddbsdk.CreateTableInput{ + TableName: aws.String("t"), + BillingMode: types.BillingModePayPerRequest, + KeySchema: []types.KeySchemaElement{{AttributeName: aws.String("id"), KeyType: types.KeyTypeHash}}, + AttributeDefinitions: []types.AttributeDefinition{ + {AttributeName: aws.String("id"), AttributeType: types.ScalarAttributeTypeS}, + }, + }) + require.NoError(t, err) + + _, err = db.PutItem(t.Context(), &ddbsdk.PutItemInput{ + TableName: aws.String("t"), + Item: map[string]types.AttributeValue{"id": &types.AttributeValueMemberS{Value: "a"}}, + }) + require.NoError(t, err) + require.Len(t, *db.meterCounters.Load(), 1) + + if tc.deleted { + _, err = db.DeleteTable(t.Context(), &ddbsdk.DeleteTableInput{TableName: aws.String("t")}) + require.NoError(t, err) + } + + h := NewHandler(db).WithJanitor(Settings{}) + h.DrainDeletedTables(t.Context()) + + assert.Len(t, *db.meterCounters.Load(), tc.wantTables) + }) + } +} diff --git a/services/dynamodb/store.go b/services/dynamodb/store.go index 82669ec88a..fea621ee38 100644 --- a/services/dynamodb/store.go +++ b/services/dynamodb/store.go @@ -232,6 +232,7 @@ type InMemoryDB struct { backups *store.Table[Backup] iteratorStore *ShardIteratorStore mu *lockmetrics.RWMutex + cleanMu *lockmetrics.RWMutex meterMu *lockmetrics.RWMutex meterCounters atomic.Pointer[map[capacityKey]*capacityCounter] deletingTables *store.Table[Table] @@ -394,6 +395,7 @@ func NewInMemoryDB() *InMemoryDB { defaultRegion: config.DefaultRegion, accountID: config.DefaultAccountID, mu: lockmetrics.New("ddb"), + cleanMu: lockmetrics.New("ddb-cleaner"), meterMu: lockmetrics.New("ddb-meter"), throttler: NewThrottler(false), txn: newTxnState(), diff --git a/services/ecs/PARITY.md b/services/ecs/PARITY.md index 1c529a9c57..265ba7e21c 100644 --- a/services/ecs/PARITY.md +++ b/services/ecs/PARITY.md @@ -76,7 +76,6 @@ gaps: [] items_still_open: - "Docker runtime container definition: firelensConfiguration and awsfirelens log routing (a task using either fails with TaskFailedToStart instead of starting the log router) and resourceRequirements (GPU) are stored but not applied; ephemeralStorage is validated (21 to 200 GiB) and reported on the task but not enforced on disk." - "Docker runtime: Task-level cpu/memory bound every container (a container without a hard memory limit gets the task memory as its ceiling, NanoCPUs is the task vCPUs) but Docker has no task cgroup, so the sum across containers is not enforced at run time (registration rejects sums above the task values). host and none network-mode containers cannot join the link-local credentials relay, and awsvpc tasks (pause container plus task network) are never adopted after an emulator restart. Managed EBS volumes: filesystemType is not applied (the Docker volume uses the local driver), volumeInitializationRate is echo only, and StartTask and ServiceRevision do not carry volumeConfigurations." - - "Docker runtime: PROVISIONING tasks in a restored snapshot are not resumed." - "ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends (CloudWatch Logs stream `ecs-execute-command-`, S3 key `/ecs-execute-command-.log`; naming from memory, unverified); KMS encryption is recorded, not performed (see External effects)." - "Kubernetes runtime (CONTAINER_RUNTIME=kubernetes, docs/kubernetes.md): one Pod per task. Refused with TaskFailedToStart: host-path/EFS/configuredAtLaunch/shared-docker volumes, networkMode host/none, pidMode/ipcMode host, privileged, devices, container restartPolicy, repositoryCredentials, FireLens, dependsOn COMPLETE/HEALTHY; ulimits/ephemeralStorage ignored; dependsOn START is not ordered; a never-ready health check stays UNKNOWN; no security-group enforcement; tasks are not adopted after a restart." structural_gaps: @@ -1364,3 +1363,8 @@ awslogs-create-group (default false) is enforced on the docker runtime: a missin - RegisterTaskDefinition/RunTask: container `memory` hard limits and `cpu` reservations whose sum exceeds the task-level value are rejected (task_definition_parameters.html: totals "must be lower than" the task value; equal is accepted); the message text is not published - ECS Exec: transcripts are capped at 1 MiB (first bytes kept), 10,000 lines and 8 KiB per line + +## 2026-11-20 (restored launches) + +Restore (via Handler.Restore, `adoptRestoredTasks`) launches again every task that was PROVISIONING, PENDING or ACTIVATING when the snapshot was taken, on a real runtime (docker, kubernetes; not the noop or nil runner), once per task, outside the backend lock, through `driveLaunch` and `completeLaunch` so failures set stoppedReason/TaskFailedToStart as a fresh launch does. RunTask only runs after the ACTIVATING step, so PROVISIONING/PENDING tasks own no containers. An ACTIVATING task is first offered to the runtime's `AdoptTask` (docker): adopted tasks go RUNNING without a second RunTask, otherwise it starts over. Emulator choices: a restored PENDING/ACTIVATING task is rewound to PROVISIONING without re-emitting an event; tasks awaiting managed-scaling capacity stay with the scaler; a task whose task definition is gone is stopped. +Restored tasks that were still launching but already had desiredStatus STOPPED are finalised to STOPPED (stopCode UserInitiated when none was recorded) and never launched. A second Restore replaces the task objects while a launch of the earlier objects may still be in flight; the stale launch is cancelled and the restored task is launched afresh. Adopted ACTIVATING tasks keep runtime-reported container health, as a fresh launch does. diff --git a/services/ecs/README.md b/services/ecs/README.md index b8276bc2cf..a8fb62c84a 100644 --- a/services/ecs/README.md +++ b/services/ecs/README.md @@ -9,7 +9,7 @@ | --- | --- | | PARITY entries audited | 65 (63 ok, 2 partial) | | Feature families | 1 (1 ok) | -| Known gaps | 5 | +| Known gaps | 4 | | Structural gaps (can't be emulated) | 5 | | Deferred items | 0 | | Resource leaks | clean | @@ -18,7 +18,6 @@ - Docker runtime container definition: firelensConfiguration and awsfirelens log routing (a task using either fails with TaskFailedToStart instead of starting the log router) and resourceRequirements (GPU) are stored but not applied; ephemeralStorage is validated (21 to 200 GiB) and reported on the task but not enforced on disk. - Docker runtime: Task-level cpu/memory bound every container (a container without a hard memory limit gets the task memory as its ceiling, NanoCPUs is the task vCPUs) but Docker has no task cgroup, so the sum across containers is not enforced at run time (registration rejects sums above the task values). host and none network-mode containers cannot join the link-local credentials relay, and awsvpc tasks (pause container plus task network) are never adopted after an emulator restart. Managed EBS volumes: filesystemType is not applied (the Docker volume uses the local driver), volumeInitializationRate is echo only, and StartTask and ServiceRevision do not carry volumeConfigurations. -- Docker runtime: PROVISIONING tasks in a restored snapshot are not resumed. - ECS Exec: sessions exist only on the docker and kubernetes runtimes with the SSM service enabled (otherwise TargetNotConnectedException); the command runs as `sh -c ` through docker exec or pods/exec, and the ssmmessages IAM checks are not applied. executeCommandConfiguration logging is delivered when the session ends (CloudWatch Logs stream `ecs-execute-command-`, S3 key `/ecs-execute-command-.log`; naming from memory, unverified); KMS encryption is recorded, not performed (see External effects). - Kubernetes runtime (CONTAINER_RUNTIME=kubernetes, docs/kubernetes.md): one Pod per task. Refused with TaskFailedToStart: host-path/EFS/configuredAtLaunch/shared-docker volumes, networkMode host/none, pidMode/ipcMode host, privileged, devices, container restartPolicy, repositoryCredentials, FireLens, dependsOn COMPLETE/HEALTHY; ulimits/ephemeralStorage ignored; dependsOn START is not ordered; a never-ready health check stays UNKNOWN; no security-group enforcement; tasks are not adopted after a restart. diff --git a/services/ecs/launch_async.go b/services/ecs/launch_async.go index 173c11d6f3..acb383182f 100644 --- a/services/ecs/launch_async.go +++ b/services/ecs/launch_async.go @@ -65,6 +65,17 @@ func (b *InMemoryBackend) launchAsync(w taskWork, clusterName string) { lt.tasks = make(map[string]*Task) } + if old, busy := lt.tasks[w.task.TaskArn]; busy { + if old == w.task { + b.mu.Unlock() + cancel() + + return + } + + lt.cancels[w.task.TaskArn]() + } + if lt.n == 0 { lt.idle = make(chan struct{}) } @@ -75,20 +86,23 @@ func (b *InMemoryBackend) launchAsync(w taskWork, clusterName string) { b.mu.Unlock() go func() { - defer b.finishLaunch(w.task.TaskArn) + defer b.finishLaunch(w.task) defer cancel() b.driveLaunch(ctx, w, clusterName) }() } -func (b *InMemoryBackend) finishLaunch(taskArn string) { +func (b *InMemoryBackend) finishLaunch(task *Task) { b.mu.Lock("finishLaunch") defer b.mu.Unlock() lt := &b.launches - delete(lt.cancels, taskArn) - delete(lt.tasks, taskArn) + if lt.tasks[task.TaskArn] == task { + delete(lt.cancels, task.TaskArn) + delete(lt.tasks, task.TaskArn) + } + lt.n-- if lt.n == 0 { @@ -176,15 +190,17 @@ func (b *InMemoryBackend) isLiveTaskLocked(task *Task) bool { func (b *InMemoryBackend) driveLaunch(ctx context.Context, w taskWork, clusterName string) { task := w.task + if w.restored && !b.prepareRestoredLaunch(ctx, w, clusterName) { + return + } + if !b.stepLaunch(ctx, task, statusProvisioning, statusPending, nil) { b.settleCancelled(ctx, task, clusterName) return } - b.mu.Lock("driveLaunch-runtime") - _, task.runtimeHealth = b.runner.(containerHealthRunner) - b.mu.Unlock() + b.setRuntimeHealth(task) activated := b.stepLaunch(ctx, task, statusPending, statusActivating, func(now time.Time) { task.PullStartedAt = &now @@ -205,6 +221,13 @@ func (b *InMemoryBackend) driveLaunch(ctx context.Context, w taskWork, clusterNa b.completeLaunch(ctx, w, clusterName, runErr) } +func (b *InMemoryBackend) setRuntimeHealth(task *Task) { + b.mu.Lock("setRuntimeHealth") + defer b.mu.Unlock() + + _, task.runtimeHealth = b.runner.(containerHealthRunner) +} + func (b *InMemoryBackend) completeLaunch(ctx context.Context, w taskWork, clusterName string, runErr error) { task := w.task superseded := false diff --git a/services/ecs/restore_adopt.go b/services/ecs/restore_adopt.go index 4ef54fc591..e6e0ecc85a 100644 --- a/services/ecs/restore_adopt.go +++ b/services/ecs/restore_adopt.go @@ -2,6 +2,7 @@ package ecs import ( "context" + "errors" "github.com/blackbirdworks/gopherstack/pkgs/logger" ) @@ -11,9 +12,16 @@ const ( containerLostExitCode = 137 ) -// adoptRestoredTasks reattaches the runner to the containers of RUNNING tasks restored from a snapshot. A task -// whose containers did not survive is stopped, as the real service stops a task whose containers are gone. +// adoptRestoredTasks resumes a restored snapshot: RUNNING tasks are re-attached to their containers and tasks +// that were mid-launch are launched again. func (b *InMemoryBackend) adoptRestoredTasks(ctx context.Context) { + b.adoptRunningTasks(ctx) + b.resumeRestoredLaunches() +} + +// adoptRunningTasks reattaches the runner to the containers of RUNNING tasks restored from a snapshot. A task +// whose containers did not survive is stopped, as the real service stops a task whose containers are gone. +func (b *InMemoryBackend) adoptRunningTasks(ctx context.Context) { ad, ok := b.runner.(taskAdopter) if !ok { return @@ -74,3 +82,131 @@ func (b *InMemoryBackend) stopLostTask(task *Task, td *TaskDefinition) { b.markTaskStoppedByContainerExit(task.TaskArn, name, containerLostExitCode) } + +var errRestoredTaskDefinition = errors.New("task definition is gone") + +// resumeRestoredLaunches launches again every restored task that was PROVISIONING, PENDING or ACTIVATING when +// the snapshot was taken. Tasks waiting for managed-scaling capacity stay with the scaler. +func (b *InMemoryBackend) resumeRestoredLaunches() { + if _, noop := b.runner.(noopRunner); b.runner == nil || noop { + return + } + + var ( + work []taskWork + stopped []*Task + ) + + b.mu.RLock("resumeRestoredLaunches") + + for _, t := range b.tasks.All() { + if !isLaunchingStatus(t.LastStatus) { + continue + } + + if t.DesiredStatus == statusStopped { + stopped = append(stopped, t) + + continue + } + + if t.AwaitingCapacity { + continue + } + + td, _ := b.taskDefByArn.Get(t.TaskDefinitionArn) + work = append(work, taskWork{task: t, td: td, restored: true}) + } + + b.mu.RUnlock() + + b.settleRestoredStops(stopped) + + for _, w := range work { + b.ensureAwslogsStreams(w.task, w.td) + b.launchAsync(w, clusterKey(clusterFromTaskARN(w.task.TaskArn))) + } +} + +// settleRestoredStops finishes tasks that were told to stop but were still launching when the snapshot was taken. +func (b *InMemoryBackend) settleRestoredStops(tasks []*Task) { + for _, task := range tasks { + b.mu.Lock("settleRestoredStops") + + done := b.isLiveTaskLocked(task) && isLaunchingStatus(task.LastStatus) && task.DesiredStatus == statusStopped + if done { + b.stopRestoredLocked(task, clusterKey(clusterFromTaskARN(task.TaskArn))) + } + + b.mu.Unlock() + + if done { + _ = b.runner.StopTask(task) + } + } +} + +func (b *InMemoryBackend) stopRestoredLocked(task *Task, clusterName string) { + now := b.clock() + task.LastStatus = statusStopped + + if task.StoppedAt == nil { + task.StoppedAt = &now + } + + if task.StopCode == "" { + task.StopCode = stopCodeUserInitiated + } + + syncContainerStatuses(task, nil) + b.emitTaskStateLocked(task) + b.deregisterTaskFromELBv2Locked(task, clusterName) + b.deregisterTaskFromCloudMapLocked(task, clusterName) + b.releaseTaskHostPortsLocked(clusterName, task) + b.releaseTaskVolumesLocked(task) + delete(b.lifecycle, task.TaskArn) + + if c, _ := b.clusters.Get(clusterName); c != nil && c.PendingTasksCount > 0 { + c.PendingTasksCount-- + } +} + +// prepareRestoredLaunch readies a restored task for driveLaunch and reports whether driveLaunch should go on. +// RunTask only starts after the ACTIVATING step, so PROVISIONING and PENDING tasks own no containers and are +// launched afresh. An ACTIVATING task may own containers: they are adopted when all survive, else it starts over. +func (b *InMemoryBackend) prepareRestoredLaunch(ctx context.Context, w taskWork, clusterName string) bool { + task := w.task + + if w.td == nil { + b.mu.Lock("prepareRestoredLaunch-missingDef") + defer b.mu.Unlock() + + if b.isLiveTaskLocked(task) && isLaunchingStatus(task.LastStatus) { + b.failLaunchLocked(task, clusterName, errRestoredTaskDefinition, b.clock()) + } + + return false + } + + b.setRuntimeHealth(task) + + b.mu.RLock("prepareRestoredLaunch") + status := task.LastStatus + b.mu.RUnlock() + + if ad, ok := b.runner.(taskAdopter); ok && status == statusActivating && ad.AdoptTask(ctx, task, w.td) { + b.completeLaunch(ctx, w, clusterName, nil) + + return false + } + + b.mu.Lock("prepareRestoredLaunch-rewind") + defer b.mu.Unlock() + + if ctx.Err() == nil && b.isLiveTaskLocked(task) && isLaunchingStatus(task.LastStatus) { + task.LastStatus = statusProvisioning + task.PullStartedAt = nil + } + + return true +} diff --git a/services/ecs/restore_resume_internal_test.go b/services/ecs/restore_resume_internal_test.go new file mode 100644 index 0000000000..b0d1dffd2f --- /dev/null +++ b/services/ecs/restore_resume_internal_test.go @@ -0,0 +1,237 @@ +package ecs + +import ( + "context" + "errors" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +var ( + errResumeBoom = errors.New("image pull failed") + errResumeDescribe = errors.New("describe during launch failed") +) + +type resumeRunner struct { + err error + gate chan struct{} + calls map[string]int + adopted map[string]bool + be *InMemoryBackend + seen map[string]string + mu sync.Mutex +} + +func newResumeRunner() *resumeRunner { + return &resumeRunner{calls: map[string]int{}, adopted: map[string]bool{}, seen: map[string]string{}} +} + +func (r *resumeRunner) RunTask(task *Task, _ *TaskDefinition) error { + if r.gate != nil { + <-r.gate + } + + r.mu.Lock() + r.calls[task.TaskArn]++ + be := r.be + r.mu.Unlock() + + if be != nil { + got, _, err := be.DescribeTasks("c", []string{task.TaskArn}) + if err != nil || len(got) != 1 { + return errResumeDescribe + } + + r.mu.Lock() + r.seen[task.TaskArn] = got[0].LastStatus + r.mu.Unlock() + } + + return r.err +} + +func (*resumeRunner) StopTask(*Task) error { return nil } + +func (r *resumeRunner) AdoptTask(_ context.Context, task *Task, _ *TaskDefinition) bool { + r.mu.Lock() + defer r.mu.Unlock() + + return r.adopted[task.TaskArn] +} + +func (r *resumeRunner) callCount(arn string) int { + r.mu.Lock() + defer r.mu.Unlock() + + return r.calls[arn] +} + +func snapshotWithStatus(t *testing.T, status string, awaiting bool) ([]byte, string) { + t.Helper() + + b1 := NewInMemoryBackend("000000000000", "us-east-1", nil) + _, err := b1.CreateCluster(CreateClusterInput{ClusterName: "c"}) + require.NoError(t, err) + + _, err = b1.RegisterTaskDefinition(RegisterTaskDefinitionInput{ + Family: "fam", ContainerDefinitions: []ContainerDefinition{{Name: "app", Image: "busybox"}}, + }) + require.NoError(t, err) + + tasks, _, err := b1.RunTask(RunTaskInput{Cluster: "c", TaskDefinition: "fam"}) + require.NoError(t, err) + require.Len(t, tasks, 1) + + arn := tasks[0].TaskArn + + b1.mu.Lock("test-set-status") + + task, _ := b1.tasks.Get(arn) + task.LastStatus = status + task.AwaitingCapacity = awaiting + + if status == statusStopped { + task.DesiredStatus = statusStopped + } + + if c, _ := b1.clusters.Get("c"); c != nil && isLaunchingStatus(status) { + c.RunningTasksCount = 0 + c.PendingTasksCount = 1 + } + + b1.mu.Unlock() + + return b1.Snapshot(t.Context()), arn +} + +func TestRestoreResumesLaunches(t *testing.T) { + t.Parallel() + + tests := []struct { + runErr error + name string + status string + wantStatus string + wantReason string + wantCalls int + adopt bool + awaiting bool + }{ + {name: "provisioning", status: statusProvisioning, wantStatus: statusRunning, wantCalls: 1}, + {name: "pending", status: statusPending, wantStatus: statusRunning, wantCalls: 1}, + {name: "activating adopted", status: statusActivating, adopt: true, wantStatus: statusRunning}, + {name: "activating lost", status: statusActivating, wantStatus: statusRunning, wantCalls: 1}, + { + name: "launch failure stops task", status: statusProvisioning, runErr: errResumeBoom, wantCalls: 1, + wantStatus: statusStopped, wantReason: "container start failed: image pull failed", + }, + { + name: "awaiting capacity left alone", status: statusProvisioning, awaiting: true, + wantStatus: statusProvisioning, + }, + {name: "running left alone", status: statusRunning, adopt: true, wantStatus: statusRunning}, + {name: "stopped left alone", status: statusStopped, wantStatus: statusStopped}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + snap, arn := snapshotWithStatus(t, tt.status, tt.awaiting) + + runner := newResumeRunner() + runner.err = tt.runErr + runner.adopted[arn] = tt.adopt + + b2 := NewInMemoryBackend("000000000000", "us-east-1", runner) + runner.be = b2 + + require.NoError(t, b2.Restore(t.Context(), snap)) + b2.adoptRestoredTasks(t.Context()) + b2.awaitLaunches() + + got, _, err := b2.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + require.Len(t, got, 1) + + assert.Equal(t, tt.wantStatus, got[0].LastStatus) + assert.Equal(t, tt.wantCalls, runner.callCount(arn)) + assert.Equal(t, tt.wantReason, got[0].StoppedReason) + + if tt.wantCalls > 0 { + assert.Equal(t, statusActivating, runner.seen[arn]) + } + + if tt.wantStatus == statusStopped && tt.wantReason != "" { + assert.Equal(t, stopCodeTaskFailedToStart, got[0].StopCode) + } + + c, _ := b2.clusters.Get("c") + require.NotNil(t, c) + + if isLaunchingStatus(tt.status) && !tt.awaiting { + assert.Zero(t, c.PendingTasksCount) + } + }) + } +} + +func TestRestoreResumesLaunchOnce(t *testing.T) { + t.Parallel() + + snap, arn := snapshotWithStatus(t, statusProvisioning, false) + + runner := newResumeRunner() + runner.gate = make(chan struct{}) + + b2 := NewInMemoryBackend("000000000000", "us-east-1", runner) + require.NoError(t, b2.Restore(t.Context(), snap)) + + b2.adoptRestoredTasks(t.Context()) + b2.adoptRestoredTasks(t.Context()) + close(runner.gate) + b2.awaitLaunches() + + assert.Equal(t, 1, runner.callCount(arn)) +} + +func TestRestoreWithoutRunnerLeavesLaunchingTasks(t *testing.T) { + t.Parallel() + + snap, arn := snapshotWithStatus(t, statusProvisioning, false) + + b2 := NewInMemoryBackend("000000000000", "us-east-1", nil) + require.NoError(t, b2.Restore(t.Context(), snap)) + b2.adoptRestoredTasks(t.Context()) + b2.awaitLaunches() + + got, _, err := b2.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + assert.Equal(t, statusProvisioning, got[0].LastStatus) +} + +func TestRestoreFailsLaunchWhenTaskDefinitionGone(t *testing.T) { + t.Parallel() + + snap, arn := snapshotWithStatus(t, statusProvisioning, false) + + runner := newResumeRunner() + b2 := NewInMemoryBackend("000000000000", "us-east-1", runner) + require.NoError(t, b2.Restore(t.Context(), snap)) + + b2.mu.Lock("test-drop-def") + b2.taskDefByArn.Reset() + b2.mu.Unlock() + + b2.adoptRestoredTasks(t.Context()) + b2.awaitLaunches() + + got, _, err := b2.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + assert.Equal(t, statusStopped, got[0].LastStatus) + assert.Contains(t, got[0].StoppedReason, errRestoredTaskDefinition.Error()) + assert.Zero(t, runner.callCount(arn)) +} diff --git a/services/ecs/restore_resume_race_internal_test.go b/services/ecs/restore_resume_race_internal_test.go new file mode 100644 index 0000000000..7534943742 --- /dev/null +++ b/services/ecs/restore_resume_race_internal_test.go @@ -0,0 +1,211 @@ +package ecs + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func snapshotMutated(t *testing.T, mutate func(task *Task)) ([]byte, string) { + t.Helper() + + b1 := NewInMemoryBackend("000000000000", "us-east-1", nil) + _, err := b1.CreateCluster(CreateClusterInput{ClusterName: "c"}) + require.NoError(t, err) + + _, err = b1.RegisterTaskDefinition(RegisterTaskDefinitionInput{ + Family: "fam", ContainerDefinitions: []ContainerDefinition{{Name: "app", Image: "busybox"}}, + }) + require.NoError(t, err) + + tasks, _, err := b1.RunTask(RunTaskInput{Cluster: "c", TaskDefinition: "fam"}) + require.NoError(t, err) + require.Len(t, tasks, 1) + + b1.mu.Lock("test-mutate") + + task, _ := b1.tasks.Get(tasks[0].TaskArn) + mutate(task) + + if c, _ := b1.clusters.Get("c"); c != nil { + c.RunningTasksCount = 0 + c.PendingTasksCount = 1 + } + + b1.mu.Unlock() + + return b1.Snapshot(t.Context()), tasks[0].TaskArn +} + +func TestSecondRestoreRelaunchesWhileFirstIsInFlight(t *testing.T) { + t.Parallel() + + snap, arn := snapshotMutated(t, func(task *Task) { task.LastStatus = statusProvisioning }) + + runner := newResumeRunner() + runner.gate = make(chan struct{}) + + b := NewInMemoryBackend("000000000000", "us-east-1", runner) + t.Cleanup(b.Close) + + require.NoError(t, b.Restore(t.Context(), snap)) + b.adoptRestoredTasks(t.Context()) + + require.NoError(t, b.Restore(t.Context(), snap)) + b.adoptRestoredTasks(t.Context()) + + close(runner.gate) + b.awaitLaunches() + + got, _, err := b.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + require.Len(t, got, 1) + assert.Equal(t, statusRunning, got[0].LastStatus) +} + +func TestRestoreStopsLaunchingTaskWithStoppedDesiredStatus(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + status string + }{ + {name: "provisioning", status: statusProvisioning}, + {name: "pending", status: statusPending}, + {name: "activating", status: statusActivating}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + snap, arn := snapshotMutated(t, func(task *Task) { + task.LastStatus = tt.status + task.DesiredStatus = statusStopped + task.StoppedReason = "Stopped by user" + }) + + runner := newResumeRunner() + runner.adopted[arn] = true + + b := NewInMemoryBackend("000000000000", "us-east-1", runner) + require.NoError(t, b.Restore(t.Context(), snap)) + b.adoptRestoredTasks(t.Context()) + b.awaitLaunches() + + got, _, err := b.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + require.Len(t, got, 1) + + assert.Equal(t, statusStopped, got[0].LastStatus) + assert.NotNil(t, got[0].StoppedAt) + assert.Equal(t, "Stopped by user", got[0].StoppedReason) + assert.Zero(t, runner.callCount(arn)) + + c, _ := b.clusters.Get("c") + require.NotNil(t, c) + assert.Zero(t, c.PendingTasksCount) + }) + } +} + +func TestRestoredServiceTasksAreNotDuplicatedByTheReconciler(t *testing.T) { + t.Parallel() + + const desired = 3 + + gated := newResumeRunner() + gated.gate = make(chan struct{}) + + b1 := NewInMemoryBackend("000000000000", "us-east-1", gated) + _, err := b1.CreateCluster(CreateClusterInput{ClusterName: "c"}) + require.NoError(t, err) + + _, err = b1.RegisterTaskDefinition(RegisterTaskDefinitionInput{ + Family: "fam", ContainerDefinitions: []ContainerDefinition{{Name: "app", Image: "busybox"}}, + }) + require.NoError(t, err) + + _, err = b1.CreateService(CreateServiceInput{ + ServiceName: "svc", Cluster: "c", TaskDefinition: "fam", DesiredCount: desired, + }) + require.NoError(t, err) + + NewReconciler(b1).RunOnce(t.Context()) + + snap := b1.Snapshot(t.Context()) + + close(gated.gate) + b1.awaitLaunches() + + runner := newResumeRunner() + b2 := NewInMemoryBackend("000000000000", "us-east-1", runner) + require.NoError(t, b2.Restore(t.Context(), snap)) + + b2.mu.Lock("test-rewind") + + launching := 0 + + for _, task := range b2.tasks.All() { + task.LastStatus = statusProvisioning + launching++ + } + + b2.mu.Unlock() + + require.Equal(t, desired, launching) + + b2.adoptRestoredTasks(t.Context()) + NewReconciler(b2).RunOnce(t.Context()) + b2.awaitLaunches() + NewReconciler(b2).RunOnce(t.Context()) + b2.awaitLaunches() + + live := 0 + + for _, task := range b2.tasks.All() { + if task.LastStatus != statusStopped { + live++ + + assert.Equal(t, statusRunning, task.LastStatus) + } + } + + assert.Equal(t, desired, live) +} + +type healthResumeRunner struct{ *resumeRunner } + +func (healthResumeRunner) SetContainerHealthHandler(func(taskArn, containerName, status string)) {} +func (healthResumeRunner) SetContainerReasonHandler(func(taskArn, containerName, reason string)) {} + +func TestAdoptedLaunchKeepsRuntimeReportedHealth(t *testing.T) { + t.Parallel() + + snap, arn := snapshotMutated(t, func(task *Task) { + task.LastStatus = statusActivating + + for i := range task.Containers { + task.Containers[i].HealthStatus = containerHealthStatusUnknown + } + }) + + runner := healthResumeRunner{newResumeRunner()} + runner.adopted[arn] = true + + b := NewInMemoryBackend("000000000000", "us-east-1", runner) + require.NoError(t, b.Restore(t.Context(), snap)) + b.adoptRestoredTasks(t.Context()) + b.awaitLaunches() + + got, _, err := b.DescribeTasks("c", []string{arn}) + require.NoError(t, err) + require.Len(t, got, 1) + require.Equal(t, statusRunning, got[0].LastStatus) + require.NotEmpty(t, got[0].Containers) + + for _, c := range got[0].Containers { + assert.Equal(t, containerHealthStatusUnknown, c.HealthStatus) + } +} diff --git a/services/ecs/task_containers.go b/services/ecs/task_containers.go index d31559d55f..7fd9bb7eb4 100644 --- a/services/ecs/task_containers.go +++ b/services/ecs/task_containers.go @@ -174,6 +174,48 @@ const ( ipPrivateClass = 10 ) +// freeIPOctets picks random last octets whose 10.0.x.y address is not in inUse. It falls back to a +// linear scan so a nearly full /16 still terminates. +func freeIPOctets(inUse map[string]bool) (int, int) { + const randomTries = 32 + + for range randomTries { + b := uuid.New() + if !inUse[fmt.Sprintf("%d.0.%d.%d", ipPrivateClass, b[0], b[1])] { + return int(b[0]), int(b[1]) + } + } + + for x := range ipOctetMod { + for y := range ipOctetMod { + if !inUse[fmt.Sprintf("%d.0.%d.%d", ipPrivateClass, x, y)] { + return x, y + } + } + } + + b := uuid.New() + + return int(b[0]), int(b[1]) +} + +// liveTaskIPsLocked returns the private IPv4s held by the cluster's non-STOPPED tasks. Caller holds b.mu. +func (b *InMemoryBackend) liveTaskIPsLocked(clusterArn string) map[string]bool { + out := make(map[string]bool) + + for _, t := range b.tasks.All() { + if t.ClusterArn != clusterArn || t.LastStatus == statusStopped { + continue + } + + if ip, ok := privateIPFromAttachments(t.Attachments); ok { + out[ip] = true + } + } + + return out +} + // safeLastN returns the last n bytes of s, padding by repetition if shorter. func safeLastN(s string, n int) string { if len(s) >= n { @@ -189,9 +231,8 @@ func safeLastN(s string, n int) string { } // newFargateTaskAttachment builds a simulated Fargate ENI attachment for a task ARN. -// Each task gets a unique ENI ID, MAC address, and private IP derived from a random UUID -// so that callers can distinguish attachments across tasks. -func newFargateTaskAttachment(taskArn, requestedSubnet string) TaskAttachment { +// Each task gets a unique ENI ID and MAC address; its private IP is random and absent from inUse. +func newFargateTaskAttachment(taskArn, requestedSubnet string, inUse map[string]bool) TaskAttachment { id := uuid.NewString() // Derive a stable but unique 12-hex-char "MAC" from the first 12 chars of the UUID @@ -202,10 +243,6 @@ func newFargateTaskAttachment(taskArn, requestedSubnet string) TaskAttachment { macRaw[6:8], macRaw[8:10], macRaw[10:12], ) - // Derive a unique /16 private IP: 10.x.y.z where x.y come from the last two - // bytes of the attachment UUID (gives 65536 distinct IPs before collision). - ipSuffix := id[len(id)-9:] // last 9 chars of UUID: "xxxxxxxx-" → no, use raw hex - _ = ipSuffix eniShort := id[:8] // 8-char prefix as eni ID suffix eniID := "eni-" + eniShort @@ -216,11 +253,10 @@ func newFargateTaskAttachment(taskArn, requestedSubnet string) TaskAttachment { subnetID = requestedSubnet } - // Build a unique private IP from the attachment UUID bytes. - octet3 := int(id[0]) % ipOctetMod - octet4 := int(id[1]) % ipOctetMod + octet3, octet4 := freeIPOctets(inUse) privateIP := fmt.Sprintf("%d.0.%d.%d", ipPrivateClass, octet3, octet4) privateDNS := fmt.Sprintf("ip-%d-0-%d-%d.ec2.internal", ipPrivateClass, octet3, octet4) + inUse[privateIP] = true return TaskAttachment{ ID: safeLastN(taskArn, eniIDLen), diff --git a/services/ecs/task_ips_test.go b/services/ecs/task_ips_test.go index 5e37be3db0..dee1af05c1 100644 --- a/services/ecs/task_ips_test.go +++ b/services/ecs/task_ips_test.go @@ -58,3 +58,42 @@ func TestRunningTaskIPv4s(t *testing.T) { }) } } + +func TestRunTaskUniquePrivateIPs(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + count int + }{ + {name: "three", count: 3}, + {name: "hundred", count: 100}, + {name: "five hundred", count: 500}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + be := ecs.NewInMemoryBackend("000000000000", "us-east-1", nil) + _, err := be.CreateCluster(ecs.CreateClusterInput{ClusterName: "c"}) + require.NoError(t, err) + + td, err := be.RegisterTaskDefinition(ecs.RegisterTaskDefinitionInput{ + Family: "f", + ContainerDefinitions: []ecs.ContainerDefinition{{Name: "app", Image: "nginx"}}, + }) + require.NoError(t, err) + + tasks, _, err := be.RunTask(ecs.RunTaskInput{ + Cluster: "c", TaskDefinition: td.TaskDefinitionArn, Count: tt.count, LaunchType: "FARGATE", + }) + require.NoError(t, err) + require.Len(t, tasks, tt.count) + + ips, err := be.RunningTaskIPv4s("c", nil) + require.NoError(t, err) + assert.Len(t, ips, tt.count) + }) + } +} diff --git a/services/ecs/tasks.go b/services/ecs/tasks.go index 15c3cffcb4..a65c744ca3 100644 --- a/services/ecs/tasks.go +++ b/services/ecs/tasks.go @@ -67,6 +67,8 @@ type taskWork struct { waiting bool // failed tasks were stopped during creation and never reach the runtime. failed bool + // restored tasks come from a snapshot taken mid-launch; driveLaunch adopts or rewinds them first. + restored bool } // RunTask starts one or more tasks on the given cluster. A per-task @@ -330,6 +332,8 @@ func (b *InMemoryBackend) createTaskEntriesLocked( var failures []Failure + inUse := b.liveTaskIPsLocked(clusterArn) + for range count { task := newTaskEntryLocked(b.region, b.accountID, clusterName, clusterArn, launchType, resolvedTags, td, input) @@ -340,7 +344,7 @@ func (b *InMemoryBackend) createTaskEntriesLocked( if launchType == launchTypeFargate || td.NetworkMode == networkModeAwsvpc { subnet := firstRequestedSubnet(input.NetworkConfiguration) - task.Attachments = []TaskAttachment{newFargateTaskAttachment(task.TaskArn, subnet)} + task.Attachments = []TaskAttachment{newFargateTaskAttachment(task.TaskArn, subnet, inUse)} } if launchType != launchTypeFargate { diff --git a/services/gcpbigquery/sdk_more_test.go b/services/gcpbigquery/sdk_more_test.go index 9c45fe4f43..13d8887545 100644 --- a/services/gcpbigquery/sdk_more_test.go +++ b/services/gcpbigquery/sdk_more_test.go @@ -62,8 +62,7 @@ func TestViewsAndDDL(t *testing.T) { require.Len(t, cm.Schema, 4) assert.Equal(t, uint64(2), cm.NumRows) - _, err = env.client.Query("DROP TABLE ddl.copy").Run(ctx) - require.NoError(t, err) + env.exec(t, "DROP TABLE ddl.copy") _, err = ds.Table("copy").Metadata(ctx) @@ -72,9 +71,13 @@ func TestViewsAndDDL(t *testing.T) { require.ErrorAs(t, err, &gerr) assert.Equal(t, http.StatusNotFound, gerr.Code) - _, err = env.client.Query("CREATE TABLE ddl.base (a INT64)").Run(ctx) + dup, err := env.client.Query("CREATE TABLE ddl.base (a INT64)").Run(ctx) require.NoError(t, err) + _, err = dup.Wait(ctx) + require.ErrorAs(t, err, &gerr) + assert.Equal(t, http.StatusConflict, gerr.Code) + it := ds.Table("v").Read(ctx) var row []bigquery.Value @@ -205,8 +208,7 @@ func TestParquetRoundTrip(t *testing.T) { ddl := "CREATE TABLE pq.src AS SELECT 1 AS id, 'a' AS s, 1.5 AS f, TRUE AS b, DATE '2024-01-02' AS d " + "UNION ALL SELECT 2, NULL, 2.5, FALSE, DATE '2024-02-03'" - _, err := env.client.Query(ddl).Run(ctx) - require.NoError(t, err) + env.exec(t, ddl) ext := bigquery.NewGCSReference("gs://bkt/p.parquet") ext.DestinationFormat = bigquery.Parquet @@ -238,8 +240,7 @@ func TestSnapshotRestore(t *testing.T) { ctx := t.Context() ds := env.dataset(t, "snap") - _, err := env.client.Query("CREATE TABLE snap.t AS SELECT 1 AS a, [1,2] AS arr, STRUCT('x' AS s) AS st").Run(ctx) - require.NoError(t, err) + env.exec(t, "CREATE TABLE snap.t AS SELECT 1 AS a, [1,2] AS arr, STRUCT('x' AS s) AS st") data := env.backend.Snapshot(ctx) require.NotEmpty(t, data) @@ -249,7 +250,7 @@ func TestSnapshotRestore(t *testing.T) { assert.Equal(t, env.rows(t, "SELECT * FROM snap.t"), other.rows(t, "SELECT * FROM snap.t")) - _, err = ds.Metadata(ctx) + _, err := ds.Metadata(ctx) require.NoError(t, err) other.backend.Reset() @@ -489,8 +490,7 @@ func TestExtractDestinationURIRules(t *testing.T) { ctx := t.Context() ds := env.dataset(t, "ex") - _, err := env.client.Query("CREATE TABLE ex.src AS SELECT 1 AS id").Run(ctx) - require.NoError(t, err) + env.exec(t, "CREATE TABLE ex.src AS SELECT 1 AS id") job, err := ds.Table("src").ExtractorTo(bigquery.NewGCSReference(tt.uri)).Run(ctx) require.NoError(t, err) diff --git a/services/gcpspanner/export_test.go b/services/gcpspanner/export_test.go index 075e6c9d49..a44945dcd3 100644 --- a/services/gcpspanner/export_test.go +++ b/services/gcpspanner/export_test.go @@ -48,6 +48,14 @@ func (b *InMemoryBackend) SetClock(now func() time.Time) { b.now = now } +// SetDumpTimeout replaces the wall-clock budget of one table-data dump. +func (b *InMemoryBackend) SetDumpTimeout(d time.Duration) { + b.mu.Lock("SetDumpTimeout") + defer b.mu.Unlock() + + b.dumpTimeout = d +} + // EmulatorRunning reports whether a data plane connection is open. func (b *InMemoryBackend) EmulatorRunning() bool { return b.emu.current() != nil } diff --git a/services/gcpspanner/store.go b/services/gcpspanner/store.go index 9460cd29fc..4f784ba076 100644 --- a/services/gcpspanner/store.go +++ b/services/gcpspanner/store.go @@ -45,6 +45,7 @@ type InMemoryBackend struct { emu *emulator keys cmek.Checker etagSeq uint64 + dumpTimeout time.Duration } // NewInMemoryBackend creates an empty backend with no data plane; see SetLauncher. @@ -52,6 +53,7 @@ func NewInMemoryBackend() *InMemoryBackend { b := &InMemoryBackend{ mu: lockmetrics.New("gcpspanner"), now: time.Now, + dumpTimeout: dumpBudget, ops: gcplro.New("gcpspanner"), wg: &sync.WaitGroup{}, instances: make(map[string]*instRec), diff --git a/services/gcpspanner/table_data.go b/services/gcpspanner/table_data.go index 4c30fa4078..4d313ae450 100644 --- a/services/gcpspanner/table_data.go +++ b/services/gcpspanner/table_data.go @@ -78,6 +78,7 @@ func (b *InMemoryBackend) collectData(ctx context.Context) map[string]dbDataSnap dialects := map[string]bool{} b.mu.RLock("collectData") + timeout := b.dumpTimeout for _, r := range b.instances { for id, d := range r.dbs { dialects[databaseName(r.pb.GetName(), id)] = databaseIsPostgres(d.pb) @@ -92,7 +93,7 @@ func (b *InMemoryBackend) collectData(ctx context.Context) map[string]dbDataSnap slices.Sort(names) - ctx, cancel := context.WithTimeout(ctx, dumpBudget) + ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() out := map[string]dbDataSnap{} diff --git a/services/gcpspanner/table_data_replay_test.go b/services/gcpspanner/table_data_replay_test.go index 2a285dd555..00a95fbd6a 100644 --- a/services/gcpspanner/table_data_replay_test.go +++ b/services/gcpspanner/table_data_replay_test.go @@ -3,6 +3,7 @@ package gcpspanner_test import ( "strings" "testing" + "time" "cloud.google.com/go/spanner/admin/database/apiv1/databasepb" "github.com/stretchr/testify/assert" @@ -75,7 +76,10 @@ func TestTableData_OverLimitDatabaseDoesNotStarveOthers(t *testing.T) { } fake, addr := newFakeEmulator(t) - e := newEnvWith(t, func(b *gcpspanner.InMemoryBackend) { b.UseEmulatorAt(addr, nil) }) + e := newEnvWith(t, func(b *gcpspanner.InMemoryBackend) { + b.UseEmulatorAt(addr, nil) + b.SetDumpTimeout(time.Hour) + }) e.createInstance(t, "data") e.createDB(t, "data") @@ -109,3 +113,18 @@ func TestTableData_OversizedReadIsSchemaOnly(t *testing.T) { snap := src.handler.Snapshot(t.Context()) assert.Less(t, len(snap), 4096) } + +func TestTableData_ExhaustedDumpBudgetIsSchemaOnly(t *testing.T) { + t.Parallel() + + fake, addr := newFakeEmulator(t) + e := newEnvWith(t, func(b *gcpspanner.InMemoryBackend) { + b.UseEmulatorAt(addr, nil) + b.SetDumpTimeout(time.Nanosecond) + }) + e.createInstance(t, "data") + e.createDB(t, "data") + fake.seed(dataDB, fakeTable{name: "T1", columns: []string{"id"}, rows: [][]*structpb.Value{{sv("1")}}}) + + assert.NotContains(t, string(e.handler.Snapshot(t.Context())), `"name":"T1"`) +} diff --git a/services/sns/export_test.go b/services/sns/export_test.go index b77a527861..1d1724e7fb 100644 --- a/services/sns/export_test.go +++ b/services/sns/export_test.go @@ -120,3 +120,6 @@ func AddOptedOutPhoneNumberForTest(b *InMemoryBackend, phoneNumber string) { defer b.mu.Unlock() b.optedOutPhoneNumbers[phoneNumber] = true } + +// SigningKeyGenerated reports whether the notification signing key has been generated. +func (b *InMemoryBackend) SigningKeyGenerated() bool { return b.signer.generated.Load() } diff --git a/services/sns/models.go b/services/sns/models.go index 0b1a76991d..87090a33aa 100644 --- a/services/sns/models.go +++ b/services/sns/models.go @@ -625,10 +625,15 @@ type ArchivedMessage struct { // in-flight deliveries that read the URL (e.g. a late server-address rewire // racing a publish already in progress). type notificationSigner struct { - privateKey *rsa.PrivateKey + material func() signingMaterial certURLValue string - certPEM []byte mu sync.RWMutex + generated atomic.Bool +} + +type signingMaterial struct { + privateKey *rsa.PrivateKey + certPEM []byte } // InMemoryBackend implements StorageBackend using an in-memory concurrency-safe store. diff --git a/services/sns/signing.go b/services/sns/signing.go index 8dc395614e..ff36e04379 100644 --- a/services/sns/signing.go +++ b/services/sns/signing.go @@ -14,6 +14,7 @@ import ( "math/big" "sort" "strings" + "sync" "time" ) @@ -33,15 +34,25 @@ func (s *notificationSigner) setCertURL(u string) { s.certURLValue = u } -// newNotificationSigner generates a fresh RSA-2048 key pair and a self-signed -// x.509 certificate. The returned signer is valid for the lifetime of the -// backend instance. region is used to construct the default certURL so the -// embedded SigningCertURL reflects the correct AWS region. +// newNotificationSigner returns a signer whose RSA-2048 key and self-signed +// certificate are generated on first use, so backends that never sign pay +// nothing at construction. func newNotificationSigner(region string) *notificationSigner { + s := ¬ificationSigner{ + certURLValue: fmt.Sprintf("https://sns.%s.amazonaws.com/SimpleNotificationService.pem", region), + } + s.material = sync.OnceValue(func() signingMaterial { + s.generated.Store(true) + + return generateSigningMaterial() + }) + + return s +} + +func generateSigningMaterial() signingMaterial { key, err := rsa.GenerateKey(rand.Reader, rsaKeyBits) if err != nil { - // Key generation failure is unrecoverable; panic with a clear message - // rather than silently falling back to mock signatures. panic("sns: failed to generate RSA key for notification signing: " + err.Error()) } @@ -62,15 +73,9 @@ func newNotificationSigner(region string) *notificationSigner { panic("sns: failed to create self-signed cert: " + err.Error()) } - certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}) - - return ¬ificationSigner{ + return signingMaterial{ privateKey: key, - certPEM: certPEM, - // certURLValue is set later via SetSigningCertBaseURL when the server address is known. - // The initial value uses the backend region so URLs are correct before - // SetSigningCertBaseURL is called (e.g. in non-HTTP test scenarios). - certURLValue: fmt.Sprintf("https://sns.%s.amazonaws.com/SimpleNotificationService.pem", region), + certPEM: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER}), } } @@ -80,7 +85,7 @@ func (s *notificationSigner) sign(canonical string) string { // Digital signature over a public notification envelope, not password // hashing. See signSHA1 below for why inline codeql markers are not used. h := sha256.Sum256([]byte(canonical)) - sig, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA256, h[:]) + sig, err := rsa.SignPKCS1v15(rand.Reader, s.material().privateKey, crypto.SHA256, h[:]) if err != nil { return "SIGN-ERROR" } @@ -103,7 +108,7 @@ func (s *notificationSigner) signSHA1(canonical string) string { // one here expecting it to work -- dismiss via the API or UI instead. //nolint:gosec // G401: AWS SNS SignatureVersion=1 spec requires SHA-1, not a password hash. h := sha1.Sum([]byte(canonical)) - sig, err := rsa.SignPKCS1v15(rand.Reader, s.privateKey, crypto.SHA1, h[:]) + sig, err := rsa.SignPKCS1v15(rand.Reader, s.material().privateKey, crypto.SHA1, h[:]) if err != nil { return "SIGN-ERROR" } diff --git a/services/sns/signing_lazy_test.go b/services/sns/signing_lazy_test.go new file mode 100644 index 0000000000..cf1cc502e4 --- /dev/null +++ b/services/sns/signing_lazy_test.go @@ -0,0 +1,32 @@ +package sns_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + "github.com/blackbirdworks/gopherstack/services/sns" +) + +func TestSigningKeyGeneratedLazily(t *testing.T) { + t.Parallel() + + tests := []struct { + use func(b *sns.InMemoryBackend) + name string + want bool + }{ + {name: "construct_only", use: func(*sns.InMemoryBackend) {}, want: false}, + {name: "cert_pem", use: func(b *sns.InMemoryBackend) { assert.NotEmpty(t, b.SigningCertPEM()) }, want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + b := sns.NewInMemoryBackend() + tt.use(b) + assert.Equal(t, tt.want, b.SigningKeyGenerated()) + }) + } +} diff --git a/services/sns/store.go b/services/sns/store.go index dc3dd5ab0c..a2e63c4911 100644 --- a/services/sns/store.go +++ b/services/sns/store.go @@ -252,7 +252,7 @@ func (b *InMemoryBackend) SetHTTPDeliveryClient(c *http.Client) { // notification's Signature field is a valid RSA-SHA1 signature over the // canonical notification string. func (b *InMemoryBackend) SigningCertPEM() []byte { - return b.signer.certPEM + return b.signer.material().certPEM } // SetSigningCertBaseURL configures the URL embedded in the SigningCertURL field diff --git a/services/transcribe/PARITY.md b/services/transcribe/PARITY.md index 54ee2e85a8..3f65eb5891 100644 --- a/services/transcribe/PARITY.md +++ b/services/transcribe/PARITY.md @@ -70,7 +70,8 @@ items_still_open: - "StartMedicalScribeJob completes at once and reports s3:///-transcript.json and -clinical-document.json without writing either object. Blockers: the clinical document is generated by AWS HealthScribe's generative model and cannot be reproduced; API_MedicalScribeOutput.html makes both URIs required and documents neither the object keys nor the transcript schema (handler_medical_scribe.go buildMedicalScribeOutputLocations, medical_scribe.go StartMedicalScribeJob)" - "Under the docker engine, ShowSpeakerLabels, ContentRedaction and MedicalContentIdentificationType jobs FAIL (the Vosk server exposes no diarization or PII detection, engine_vosk.go; pipeline.go recognize); custom vocabularies and custom language models are not applied to recognition (no Vosk hotword or model-adaptation API). Vocabulary filters (mask, remove, tag) are applied to transcription and call analytics words." - "IdentifyLanguage/IdentifyMultipleLanguages report the first LanguageOptions entry with a fixed IdentifiedLanguageScore; the Vosk server has no language identification (transcription_jobs.go syntheticIdentifiedLanguageScore)" - - "Docker engine decodes 16-bit PCM WAV only: FLAC/MP3/MP4/OGG/AMR/WebM decoding needs a decoder dependency that go.mod does not carry (pipeline.go recognize rejects them). Call Analytics sentiment, loudness, talk-time, categories and summaries are not produced." + - "Docker engine cannot decode MP4/M4A (AAC), AMR, WebM or Ogg Opus: no maintained pure-Go decoder is in go.mod (pipeline.go recognize fails those jobs). Call Analytics sentiment, loudness, talk-time, categories and summaries are not produced." + - "Emulator limit: the docker engine takes one PCM buffer per channel, so decoded audio is capped at 64 MiB of 16 kHz 16-bit PCM across all channels (about 33 minutes mono, 16 minutes per channel for two channels); longer jobs fail with \"Invalid file size: file size too large\" although AWS accepts up to 4 hours (audio_decode.go maxDecodedBytes). The media object is still read whole, up to the 2 GB limit, before decoding." - "Medical transcript and Call Analytics JSON follow the batch schema and the documented post-call field names respectively; PHI entity annotations and the Categories/IssuesDetected sections are not emitted (unverified against a live AWS document)." structural_gaps: - "CallAnalyticsJobDetails.Skipped: skipped features (insufficient conversation content, safety guidelines) come from analysing real audio; the emulator evaluates none of the Call Analytics features." @@ -614,3 +615,16 @@ StartTranscriptionJob (immediate and deferred, on completion), StartMedicalTrans - Without the docker engine, jobs finish with a valid transcript document with an empty transcript and no items (no words are invented); real recognition needs the docker engine. - Vocabulary filter matching is exact on the case-folded word; VocabularyFilterFileUri files are read through the S3 emulator, one word per line, capped at 1 MiB and 50000 words. Mask, remove and tag follow vocabulary-filtering.html (mask replaces with ***, remove deletes, tag adds "vocabularyFilterMatch": true to the item). + +## 2026-11-20 (audio decoding) + +The docker engine decodes WAV (8/16/24/32-bit PCM, float32/64, A-law, mu-law, WAVE_FORMAT_EXTENSIBLE), FLAC (mewkiz/flac), MP3 (go-mp3) and Ogg Vorbis (oggvorbis), all pure Go. Audio is streamed in 4096-frame chunks, converted to 16 kHz 16-bit PCM (engine rate) and downmixed unless the job needs channels; Ogg Opus, MP4/AAC, AMR and WebM fail the job ("cannot decode media"). + +Emulator choices (vendor-undocumented): +- Resampling: box-average (area) filtering when decimating, linear interpolation when interpolating; no polyphase/sinc filter. +- Corrupt, truncated or undecodable media (including a decoder panic, recovered at the adapter boundary) fails with the documented "Unsupported media format"; the SDK lists no dedicated reason. +- More than 4 hours of audio, or more than 64 MiB of decoded PCM (see items_still_open), fails with "Invalid file size: file size too large". The 4-hour batch limit is the service quota from memory, not in the SDK comments; the 2 GB size limit is unchanged. +- MP3: go-mp3 always emits stereo, so mono is detected from the first frame header's channel mode. A truncated MP3 ends silently at the last full frame (the decoder's own behaviour); a truncated FLAC fails. +- Header checks (channel count, MediaSampleRateHertz equals the detected rate; omitted means no check) run for WAV/FLAC/MP3/Ogg even without an engine; the rate is checked against the source rate, before resampling. Without an engine a container the decoders cannot open (placeholder bytes behind a valid magic, a WAV encoding with no decoder) still completes as before; only a malformed WAV, a channel count above two or a rate mismatch fails. +- Header-declared sizes never drive allocation: Ogg Vorbis comment and codebook headers and ID3v2 tag sizes are pre-checked against the file (vorbis_guard.go, audio_decode.go id3v2Size) because the third-party decoders allocate from them. Deleting a job cancels its in-flight decode and recognition. +- Call Analytics talk-time/non-talk-time/loudness were not added: the SDK defines no shape for the post-call document, so the fields would rest on unverified memory. diff --git a/services/transcribe/README.md b/services/transcribe/README.md index 608cee6d69..36df76649f 100644 --- a/services/transcribe/README.md +++ b/services/transcribe/README.md @@ -9,7 +9,7 @@ | --- | --- | | PARITY entries audited | 44 (44 ok) | | Feature families | 8 (8 ok) | -| Known gaps | 5 | +| Known gaps | 6 | | Structural gaps (can't be emulated) | 2 | | Deferred items | 0 | | Resource leaks | clean | @@ -19,7 +19,8 @@ - StartMedicalScribeJob completes at once and reports s3:///-transcript.json and -clinical-document.json without writing either object. Blockers: the clinical document is generated by AWS HealthScribe's generative model and cannot be reproduced; API_MedicalScribeOutput.html makes both URIs required and documents neither the object keys nor the transcript schema (handler_medical_scribe.go buildMedicalScribeOutputLocations, medical_scribe.go StartMedicalScribeJob) - Under the docker engine, ShowSpeakerLabels, ContentRedaction and MedicalContentIdentificationType jobs FAIL (the Vosk server exposes no diarization or PII detection, engine_vosk.go; pipeline.go recognize); custom vocabularies and custom language models are not applied to recognition (no Vosk hotword or model-adaptation API). Vocabulary filters (mask, remove, tag) are applied to transcription and call analytics words. - IdentifyLanguage/IdentifyMultipleLanguages report the first LanguageOptions entry with a fixed IdentifiedLanguageScore; the Vosk server has no language identification (transcription_jobs.go syntheticIdentifiedLanguageScore) -- Docker engine decodes 16-bit PCM WAV only: FLAC/MP3/MP4/OGG/AMR/WebM decoding needs a decoder dependency that go.mod does not carry (pipeline.go recognize rejects them). Call Analytics sentiment, loudness, talk-time, categories and summaries are not produced. +- Docker engine cannot decode MP4/M4A (AAC), AMR, WebM or Ogg Opus: no maintained pure-Go decoder is in go.mod (pipeline.go recognize fails those jobs). Call Analytics sentiment, loudness, talk-time, categories and summaries are not produced. +- Emulator limit: the docker engine takes one PCM buffer per channel, so decoded audio is capped at 64 MiB of 16 kHz 16-bit PCM across all channels (about 33 minutes mono, 16 minutes per channel for two channels); longer jobs fail with "Invalid file size: file size too large" although AWS accepts up to 4 hours (audio_decode.go maxDecodedBytes). The media object is still read whole, up to the 2 GB limit, before decoding. - Medical transcript and Call Analytics JSON follow the batch schema and the documented post-call field names respectively; PHI entity annotations and the Categories/IssuesDetected sections are not emitted (unverified against a live AWS document). ### Structural gaps diff --git a/services/transcribe/audio_decode.go b/services/transcribe/audio_decode.go new file mode 100644 index 0000000000..a2dc32e1fb --- /dev/null +++ b/services/transcribe/audio_decode.go @@ -0,0 +1,658 @@ +package transcribe + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + + "github.com/hajimehoshi/go-mp3" + "github.com/jfreymuth/oggvorbis" + "github.com/mewkiz/flac" + "github.com/mewkiz/flac/frame" +) + +const ( + engineSampleRate = 16000 + maxAudioSeconds = 4 * 3600 + maxDecodedBytes = 64 << 20 + maxIdleReads = 1 << 12 + decodeChunkFrames = 4096 + mp3FrameBytes = 4 + mp3ScanLimit = 1 << 16 + id3v2HeaderLen = 10 + syncsafeBits = 7 + wavFmtExtMin = 26 + wavFmtExtSubTag = 24 + maxPCMWidth = 4 + float32Width = 4 + float64Width = 8 + g711Mantissa = 0x0F + g711Segment = 0x70 + g711SegShift = 4 + aLawXor = 0x55 + syncsafeMask = 0x7F + unsigned8Bias = 128 + g711MuShift = 3 + pcmSampleBytes = 2 +) + +const ( + wavFormatFloat = 3 + wavFormatALaw = 6 + wavFormatMuLaw = 7 +) + +var ( + errDecode = errors.New("audio decode failed") + errAudioLength = errors.New("audio longer than the batch limit") +) + +// audioSource yields interleaved 16-bit frames; read may return frames together with io.EOF. +type audioSource interface { + rate() int + channels() int + // frames is the total frame count when the container header states it, else -1. + frames() int64 + read(dst []int16) (int, error) +} + +// decodedAudio is mono-or-per-channel 16-bit little-endian PCM at engineSampleRate. +type decodedAudio struct { + channels [][]byte + millis int +} + +func safely(fn func() error) (err error) { + defer func() { + if r := recover(); r != nil { + err = fmt.Errorf("%w: %v", errDecode, r) + } + }() + + return fn() +} + +// openAudio builds a source for a sniffed container; formats without a decoder return errDecode. +func openAudio(format string, data []byte) (audioSource, error) { + var src audioSource + + err := safely(func() error { + var openErr error + + switch format { + case mediaWAV: + src, openErr = openWAV(data) + case mediaFLAC: + src, openErr = openFLAC(data) + case mediaMP3: + src, openErr = openMP3(data) + case mediaOGG: + src, openErr = openOGG(data) + default: + openErr = fmt.Errorf("%w: no decoder for %s", errDecode, format) + } + + return openErr + }) + if err != nil { + return nil, err + } + + return src, nil +} + +func decodable(format string) bool { + switch format { + case mediaWAV, mediaFLAC, mediaMP3, mediaOGG: + return true + default: + return false + } +} + +// decodeAudio streams src into 16 kHz 16-bit PCM, downmixing to one channel when mono is set; +// more than maxSeconds of source audio, or maxDecodedBytes of output, yields errAudioLength. +func decodeAudio(ctx context.Context, src audioSource, mono bool, maxSeconds int) (decodedAudio, error) { + srcCh := src.channels() + if srcCh < 1 || srcCh > dualChannel || src.rate() < 1 { + return decodedAudio{}, fmt.Errorf("%w: %d channels at %d Hz", errDecode, srcCh, src.rate()) + } + + outCh := srcCh + + if mono { + outCh = 1 + } + + mix := &mixer{srcCh: srcCh, mono: mono, rs: make([]resampler, outCh), out: make([][]byte, outCh)} + + for c := range mix.rs { + mix.rs[c] = newResampler(src.rate(), engineSampleRate) + } + + buf := make([]int16, decodeChunkFrames*srcCh) + limit := int64(maxSeconds) * int64(src.rate()) + + var ( + total int64 + idle int + ) + + for { + if ctx.Err() != nil { + return decodedAudio{}, ctx.Err() + } + + var n int + + err := safely(func() error { + var readErr error + + n, readErr = src.read(buf) + + return readErr + }) + + mix.push(buf, n) + + total += int64(n) + if total > limit || mix.size() > maxDecodedBytes { + return decodedAudio{}, errAudioLength + } + + if idle = nextIdle(idle, n); idle > maxIdleReads { + return decodedAudio{}, fmt.Errorf("%w: decoder made no progress", errDecode) + } + + if errors.Is(err, io.EOF) { + break + } + + if err != nil { + return decodedAudio{}, err + } + } + + return decodedAudio{channels: mix.out, millis: int(total * millisPerSecond / int64(src.rate()))}, nil +} + +func nextIdle(idle, n int) int { + if n > 0 { + return 0 + } + + return idle + 1 +} + +// mixer resamples interleaved frames into per-channel output, averaging channels when mono. +type mixer struct { + rs []resampler + out [][]byte + srcCh int + mono bool +} + +func (m *mixer) size() int { + total := 0 + for _, o := range m.out { + total += len(o) + } + + return total +} + +func (m *mixer) push(buf []int16, frames int) { + for i := range frames { + frame := buf[i*m.srcCh : (i+1)*m.srcCh] + + if !m.mono { + for c, v := range frame { + m.out[c] = m.rs[c].push(v, m.out[c]) + } + + continue + } + + sum := 0 + for _, v := range frame { + sum += int(v) + } + + m.out[0] = m.rs[0].push(int16(sum/m.srcCh), m.out[0]) //nolint:gosec // an average of int16 fits int16 + } +} + +// resampler converts a mono stream to a target rate: box-average (area) filtering when +// decimating, linear interpolation when interpolating. +type resampler struct { + step float64 + acc float64 + need float64 + prev float64 + pos float64 + primed bool +} + +func newResampler(from, to int) resampler { + step := float64(from) / float64(to) + + return resampler{step: step, need: step} +} + +func (r *resampler) push(x int16, dst []byte) []byte { + const eps = 1e-9 + + v := float64(x) + + switch { + case r.step == 1: + return binary.LittleEndian.AppendUint16(dst, uint16(x)) //nolint:gosec // int16 bit reinterpretation + case r.step > 1: + avail := 1.0 + + for avail > eps { + take := math.Min(avail, r.need) + r.acc += v * take + r.need -= take + avail -= take + + if r.need <= eps { + dst = appendClamped(dst, r.acc/r.step) + r.acc = 0 + r.need = r.step + } + } + + return dst + default: + if !r.primed { + r.primed = true + r.prev = v + + return dst + } + + for r.pos < 1 { + dst = appendClamped(dst, r.prev+(v-r.prev)*r.pos) + r.pos += r.step + } + + r.pos-- + r.prev = v + + return dst + } +} + +func appendClamped(dst []byte, v float64) []byte { + return binary.LittleEndian.AppendUint16(dst, uint16(clampInt16(v))) //nolint:gosec // int16 bit reinterpretation +} + +func clampInt16(v float64) int16 { + if math.IsNaN(v) { + return 0 + } + + return int16(math.Max(math.MinInt16, math.Min(math.MaxInt16, math.Round(v)))) +} + +type wavSource struct { + info wavInfo + codec int + width int + pos int +} + +func wavCodecWidthOK(codec, width int) bool { + switch codec { + case wavFormatPCM: + return width >= 1 && width <= maxPCMWidth + case wavFormatFloat: + return width == float32Width || width == float64Width + case wavFormatALaw, wavFormatMuLaw: + return width == 1 + default: + return false + } +} + +func openWAV(data []byte) (audioSource, error) { + info, err := parseWAV(data) + if err != nil { + return nil, err + } + + codec := info.codec() + width := info.bits / bitsPerByte + + if info.channels <= 0 || info.sampleRate <= 0 || info.bits%bitsPerByte != 0 || !wavCodecWidthOK(codec, width) { + return nil, fmt.Errorf("%w: unsupported WAV encoding tag %d at %d bits", errDecode, codec, info.bits) + } + + return &wavSource{info: info, codec: codec, width: width}, nil +} + +func (s *wavSource) rate() int { return s.info.sampleRate } +func (s *wavSource) channels() int { return s.info.channels } + +func (s *wavSource) frames() int64 { return int64(len(s.info.pcm) / (s.info.channels * s.width)) } + +func (s *wavSource) read(dst []int16) (int, error) { + frameBytes := s.info.channels * s.width + n := min(len(dst)/s.info.channels, (len(s.info.pcm)-s.pos)/frameBytes) + + for i := range n * s.info.channels { + dst[i] = s.sample(s.info.pcm[s.pos : s.pos+s.width]) + s.pos += s.width + } + + if n == 0 { + return 0, io.EOF + } + + return n, nil +} + +func (s *wavSource) sample(b []byte) int16 { + switch s.codec { + case wavFormatALaw: + return decodeALaw(b[0]) + case wavFormatMuLaw: + return decodeMuLaw(b[0]) + case wavFormatFloat: + if s.width == float32Width { + return clampInt16(float64(math.Float32frombits(binary.LittleEndian.Uint32(b))) * math.MaxInt16) + } + + return clampInt16(math.Float64frombits(binary.LittleEndian.Uint64(b)) * math.MaxInt16) + } + + if s.width == 1 { + return int16(int(b[0])-unsigned8Bias) << bitsPerByte //nolint:gosec // 8-bit sample, fits int16 + } + + return int16(binary.LittleEndian.Uint16(b[s.width-2:])) //nolint:gosec // top two bytes of a signed sample +} + +func decodeMuLaw(b byte) int16 { + const bias = 0x84 + + u := ^b + t := (int(u&g711Mantissa) << g711MuShift) + bias + t <<= (u & g711Segment) >> g711SegShift + + if u&0x80 != 0 { + return int16(bias - t) //nolint:gosec // G.711 magnitude fits int16 + } + + return int16(t - bias) //nolint:gosec // G.711 magnitude fits int16 +} + +func decodeALaw(b byte) int16 { + a := b ^ aLawXor + t := int(a&g711Mantissa) << g711SegShift + seg := (a & g711Segment) >> g711SegShift + + switch seg { + case 0: + t += 8 + case 1: + t += 0x108 + default: + t += 0x108 + t <<= seg - 1 + } + + if a&0x80 != 0 { + return int16(t) + } + + return int16(-t) +} + +type flacSource struct { + stream *flac.Stream + pending []int16 + shift int + ch int +} + +func openFLAC(data []byte) (audioSource, error) { + stream, err := flac.New(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("%w: %w", errDecode, err) + } + + info := stream.Info + if info.SampleRate == 0 || info.NChannels == 0 || info.BitsPerSample == 0 { + return nil, fmt.Errorf("%w: empty FLAC stream info", errDecode) + } + + return &flacSource{stream: stream, ch: int(info.NChannels), shift: int(info.BitsPerSample) - pcmBits}, nil +} + +func (s *flacSource) rate() int { return int(s.stream.Info.SampleRate) } +func (s *flacSource) channels() int { return s.ch } + +func (s *flacSource) frames() int64 { + if s.stream.Info.NSamples == 0 || s.stream.Info.NSamples > math.MaxInt64 { + return -1 + } + + return int64(s.stream.Info.NSamples) +} + +func (s *flacSource) read(dst []int16) (int, error) { + if len(s.pending) == 0 { + pcm, err := s.nextFrame() + if err != nil { + return 0, err + } + + s.pending = pcm + } + + n := min(len(dst)/s.ch, len(s.pending)/s.ch) + copy(dst, s.pending[:n*s.ch]) + s.pending = s.pending[n*s.ch:] + + return n, nil +} + +func (s *flacSource) nextFrame() ([]int16, error) { + f, err := s.stream.ParseNext() + if err != nil { + if errors.Is(err, io.EOF) { + return nil, io.EOF + } + + return nil, fmt.Errorf("%w: %w", errDecode, err) + } + + if len(f.Subframes) != s.ch { + return nil, fmt.Errorf("%w: FLAC frame has %d channels, want %d", errDecode, len(f.Subframes), s.ch) + } + + for _, sf := range f.Subframes { + if len(sf.Samples) != f.Subframes[0].NSamples { + return nil, fmt.Errorf("%w: FLAC subframe length mismatch", errDecode) + } + } + + return s.interleave(f), nil +} + +func (s *flacSource) interleave(f *frame.Frame) []int16 { + n := f.Subframes[0].NSamples + out := make([]int16, 0, n*s.ch) + + for i := range n { + for c := range s.ch { + v := f.Subframes[c].Samples[i] + if s.shift >= 0 { + v >>= s.shift + } else { + v <<= -s.shift + } + + out = append(out, int16(v)) //nolint:gosec // shifted to 16-bit range + } + } + + return out +} + +type mp3Source struct { + dec *mp3.Decoder + raw []byte + mono bool +} + +func openMP3(data []byte) (audioSource, error) { + if id3v2Size(data) > len(data) { + return nil, fmt.Errorf("%w: ID3v2 tag larger than the file", errDecode) + } + + dec, err := mp3.NewDecoder(struct{ io.Reader }{bytes.NewReader(data)}) + if err != nil { + return nil, fmt.Errorf("%w: %w", errDecode, err) + } + + return &mp3Source{dec: dec, mono: mp3IsMono(data)}, nil +} + +func (s *mp3Source) rate() int { return s.dec.SampleRate() } + +func (s *mp3Source) channels() int { + if s.mono { + return 1 + } + + return dualChannel +} + +func (s *mp3Source) frames() int64 { return -1 } + +func (s *mp3Source) read(dst []int16) (int, error) { + ch := s.channels() + want := len(dst) / ch + + if cap(s.raw) < want*mp3FrameBytes { + s.raw = make([]byte, want*mp3FrameBytes) + } + + raw := s.raw[:want*mp3FrameBytes] + got, err := io.ReadFull(s.dec, raw) + n := got / mp3FrameBytes + + for i := range n { + for c := range ch { + off := i*mp3FrameBytes + c*pcmSampleBytes + dst[i*ch+c] = int16(binary.LittleEndian.Uint16(raw[off:])) //nolint:gosec // PCM reinterpretation + } + } + + if errors.Is(err, io.ErrUnexpectedEOF) { + err = io.EOF + } + + if err != nil && !errors.Is(err, io.EOF) { + return n, fmt.Errorf("%w: %w", errDecode, err) + } + + return n, err +} + +// mp3IsMono reads the channel mode of the first frame header; go-mp3 always emits stereo. +func mp3IsMono(data []byte) bool { + const ( + monoMode = 3 + modeShift = 6 + headerLen = 4 + layerMask = 0x06 + layerNone = 0 + versionBad = 0x18 + ) + + pos := id3v2Size(data) + + end := min(len(data)-headerLen, pos+mp3ScanLimit) + + for i := pos; i <= end; i++ { + if data[i] == 0xFF && data[i+1]&0xE0 == 0xE0 && data[i+1]&layerMask != layerNone && + data[i+1]&versionBad != 0x08 { + return data[i+3]>>modeShift == monoMode + } + } + + return false +} + +// id3v2Size is the length of a leading ID3v2 tag including its header, or 0 when there is none. +func id3v2Size(data []byte) int { + if len(data) < id3v2HeaderLen || !bytes.HasPrefix(data, []byte("ID3")) { + return 0 + } + + size := 0 + for _, b := range data[6:id3v2HeaderLen] { + size = size<>(8*i))) + } + } + } + } + + fmtLen := 16 + if spec.extensible { + fmtLen = 40 + } + + tag := spec.tag + if spec.extensible { + tag = wavFormatExtensible + } + + out := []byte("RIFF") + out = binary.LittleEndian.AppendUint32(out, uint32(4+8+fmtLen+8+len(data))) + out = append(out, "WAVEfmt "...) + out = binary.LittleEndian.AppendUint32(out, uint32(fmtLen)) + out = binary.LittleEndian.AppendUint16(out, uint16(tag)) + out = binary.LittleEndian.AppendUint16(out, uint16(spec.channels)) + out = binary.LittleEndian.AppendUint32(out, uint32(spec.rate)) + out = binary.LittleEndian.AppendUint32(out, uint32(spec.rate*spec.channels*width)) + out = binary.LittleEndian.AppendUint16(out, uint16(spec.channels*width)) + out = binary.LittleEndian.AppendUint16(out, uint16(spec.bits)) + + if spec.extensible { + out = binary.LittleEndian.AppendUint16(out, 22) + out = binary.LittleEndian.AppendUint16(out, uint16(spec.bits)) + out = binary.LittleEndian.AppendUint32(out, 0) + out = binary.LittleEndian.AppendUint16(out, uint16(spec.tag)) + out = append(out, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71) + } + + out = append(out, "data"...) + out = binary.LittleEndian.AppendUint32(out, uint32(len(data))) + + return append(out, data...) +} + +// encodeG711 is the reference G.711 encoder, used only to build fixtures. +func encodeG711(pcm int16, alaw bool) byte { + best, bestErr := byte(0), math.MaxInt + + for c := range 256 { + var got int16 + if alaw { + got = decodeALaw(byte(c)) + } else { + got = decodeMuLaw(byte(c)) + } + + if d := int(math.Abs(float64(int(got) - int(pcm)))); d < bestErr { + best, bestErr = byte(c), d + } + } + + return best +} + +func decodeBytes(t *testing.T, media []byte, format string, mono bool) (audioSource, decodedAudio) { + t.Helper() + + src, err := openAudio(format, media) + require.NoError(t, err) + + audio, err := decodeAudio(t.Context(), src, mono, maxAudioSeconds) + require.NoError(t, err) + + return src, audio +} + +func TestDecodeWAVVariants(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + spec wavSpec + }{ + {name: "pcm8", spec: wavSpec{tag: 1, bits: 8, channels: 1, rate: 16000}}, + {name: "pcm16", spec: wavSpec{tag: 1, bits: 16, channels: 1, rate: 16000}}, + {name: "pcm24", spec: wavSpec{tag: 1, bits: 24, channels: 1, rate: 16000}}, + {name: "pcm32", spec: wavSpec{tag: 1, bits: 32, channels: 1, rate: 16000}}, + {name: "float32", spec: wavSpec{tag: 3, bits: 32, channels: 1, rate: 16000}}, + {name: "float64", spec: wavSpec{tag: 3, bits: 64, channels: 1, rate: 16000}}, + {name: "alaw", spec: wavSpec{tag: 6, bits: 8, channels: 1, rate: 16000}}, + {name: "mulaw", spec: wavSpec{tag: 7, bits: 8, channels: 1, rate: 16000}}, + {name: "extensible pcm24", spec: wavSpec{tag: 1, bits: 24, channels: 1, rate: 16000, extensible: true}}, + {name: "extensible float32", spec: wavSpec{tag: 3, bits: 32, channels: 1, rate: 16000, extensible: true}}, + {name: "stereo downmix", spec: wavSpec{tag: 1, bits: 16, channels: 2, rate: 16000}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + media := buildWAV(tt.spec, toneSamples(tt.spec.rate, 0.5)) + src, audio := decodeBytes(t, media, mediaWAV, true) + + require.Len(t, audio.channels, 1) + assert.Equal(t, tt.spec.channels, src.channels()) + assert.Equal(t, 500, audio.millis) + + samples := pcmInt16(audio.channels[0]) + assert.Len(t, samples, 8000) + assert.Greater(t, goertzel(samples), 0.9) + + peak := 0.0 + for _, v := range samples { + peak = math.Max(peak, math.Abs(float64(v))) + } + + assert.Greater(t, peak, 1000.0) + }) + } +} + +func TestDecodeWAVRejects(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + spec wavSpec + }{ + {name: "adpcm", spec: wavSpec{tag: 2, bits: 4, channels: 1, rate: 16000}}, + {name: "pcm12", spec: wavSpec{tag: 1, bits: 12, channels: 1, rate: 16000}}, + {name: "alaw16", spec: wavSpec{tag: 6, bits: 16, channels: 1, rate: 16000}}, + {name: "zero rate", spec: wavSpec{tag: 1, bits: 16, channels: 1, rate: 0}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + _, err := openAudio(mediaWAV, buildWAV(tt.spec, toneSamples(16000, 0.01))) + require.ErrorIs(t, err, errDecode) + }) + } +} + +func TestResamplerRates(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + rate int + }{ + {name: "8k up", rate: 8000}, + {name: "11k up", rate: 11025}, + {name: "22k down", rate: 22050}, + {name: "44k down", rate: 44100}, + {name: "48k down", rate: 48000}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + media := buildWAV(wavSpec{tag: 1, bits: 16, channels: 1, rate: tt.rate}, toneSamples(tt.rate, 1)) + _, audio := decodeBytes(t, media, mediaWAV, true) + samples := pcmInt16(audio.channels[0]) + + assert.InDelta(t, engineSampleRate, len(samples), 2) + assert.Greater(t, goertzel(samples), 0.9) + }) + } +} + +func TestDecodeKeepsChannelsSeparate(t *testing.T) { + t.Parallel() + + const rate = 16000 + + left := toneSamples(rate, 0.25) + data := make([]byte, 0, len(left)*4) + + for _, v := range left { + data = binary.LittleEndian.AppendUint16(data, uint16(int16(v*8000))) + data = binary.LittleEndian.AppendUint16(data, 0) + } + + stereo := buildWAV(wavSpec{tag: 1, bits: 16, channels: 2, rate: rate}, nil) + stereo = append(stereo[:len(stereo)-4], binary.LittleEndian.AppendUint32(nil, uint32(len(data)))...) + stereo = append(stereo, data...) + + _, audio := decodeBytes(t, stereo, mediaWAV, false) + require.Len(t, audio.channels, 2) + assert.Greater(t, goertzel(pcmInt16(audio.channels[0])), 0.9) + + for _, v := range pcmInt16(audio.channels[1]) { + require.Zero(t, v) + } +} + +func encodeFLAC(t *testing.T, rate, bits int, channels [][]int32) []byte { + t.Helper() + + n := len(channels[0]) + info := &meta.StreamInfo{ + BlockSizeMin: uint16(n), BlockSizeMax: uint16(n), SampleRate: uint32(rate), + NChannels: uint8(len(channels)), BitsPerSample: uint8(bits), NSamples: uint64(n), + } + + var buf bytes.Buffer + + enc, err := flac.NewEncoder(&buf, info) + require.NoError(t, err) + + layout := frame.ChannelsMono + + switch len(channels) { + case 2: + layout = frame.ChannelsLR + case 3: + layout = frame.ChannelsLRC + } + + f := &frame.Frame{ + HasFixedBlockSize: true, BlockSize: uint16(n), SampleRate: uint32(rate), Channels: layout, + BitsPerSample: uint8(bits)} + + for _, c := range channels { + f.Subframes = append(f.Subframes, &frame.Subframe{ + Pred: frame.PredVerbatim, Samples: c, NSamples: n, + }) + } + + require.NoError(t, enc.WriteFrame(f)) + require.NoError(t, enc.Close()) + + return buf.Bytes() +} + +func intTone(rate int, seconds float64, bits int) []int32 { + tone := toneSamples(rate, seconds) + out := make([]int32, len(tone)) + + for i, v := range tone { + out[i] = int32(v * 0.5 * float64(int64(1)<<(bits-1))) + } + + return out +} + +func TestDecodeFLAC(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + rate int + bits int + channels int + samples int + }{ + {name: "mono16", rate: 16000, bits: 16, channels: 1, samples: 8000}, + {name: "mono24", rate: 16000, bits: 24, channels: 1, samples: 8000}, + {name: "stereo16 48k", rate: 48000, bits: 16, channels: 2, samples: 8000}, + {name: "mono8 8k", rate: 8000, bits: 8, channels: 1, samples: 8000}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + chans := make([][]int32, tt.channels) + for c := range chans { + chans[c] = intTone(tt.rate, 0.5, tt.bits) + } + + media := encodeFLAC(t, tt.rate, tt.bits, chans) + require.Equal(t, mediaFLAC, sniffMediaFormat(media)) + + src, audio := decodeBytes(t, media, mediaFLAC, true) + assert.Equal(t, tt.rate, src.rate()) + assert.Equal(t, tt.channels, src.channels()) + assert.Equal(t, int64(tt.rate/2), src.frames()) + assert.Equal(t, 500, audio.millis) + + samples := pcmInt16(audio.channels[0]) + assert.InDelta(t, tt.samples, len(samples), 2) + assert.Greater(t, goertzel(samples), 0.9) + }) + } +} + +func silentMP3(frames int, mono bool) []byte { + const ( + frameLen = 417 + monoSideInfo = 17 + ) + + header := []byte{0xFF, 0xFB, 0x90, 0x00} + if mono { + header[3] = 0xC0 + } + + out := make([]byte, 0, frames*frameLen) + + for range frames { + f := make([]byte, frameLen) + copy(f, header) + out = append(out, f...) + } + + return out +} + +func TestDecodeMP3(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + mono bool + channels int + }{ + {name: "stereo", channels: 2}, + {name: "mono", mono: true, channels: 1}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + const frames = 40 + + media := silentMP3(frames, tt.mono) + require.Equal(t, mediaMP3, sniffMediaFormat(media)) + + src, audio := decodeBytes(t, media, mediaMP3, false) + assert.Equal(t, 44100, src.rate()) + assert.Equal(t, tt.channels, src.channels()) + require.Len(t, audio.channels, tt.channels) + + want := frames * 1152 * engineSampleRate / 44100 + assert.InDelta(t, want, len(audio.channels[0])/2, float64(want)/10) + assert.Greater(t, audio.millis, 900) + }) + } +} + +// testdata/vorbis.ogg is testdata/test.ogg from github.com/jfreymuth/oggvorbis v1.0.5 (MIT), +// copied from the module cache; no pure-Go Vorbis encoder or ogg tool exists on the build host. +func TestDecodeOggVorbis(t *testing.T) { + t.Parallel() + + media, err := os.ReadFile("testdata/vorbis.ogg") + require.NoError(t, err) + require.Equal(t, mediaOGG, sniffMediaFormat(media)) + + src, audio := decodeBytes(t, media, mediaOGG, true) + require.Positive(t, src.rate()) + require.Positive(t, src.frames()) + + want := int(src.frames() * engineSampleRate / int64(src.rate())) + require.Len(t, audio.channels, 1) + + samples := pcmInt16(audio.channels[0]) + assert.InDelta(t, want, len(samples), float64(want)/20+2) + + var energy float64 + for _, v := range samples { + energy += float64(v) * float64(v) + } + + assert.Positive(t, energy) +} + +func TestDecodeCorruptInputs(t *testing.T) { + t.Parallel() + + flacOK := encodeFLAC(t, 16000, 16, [][]int32{intTone(16000, 0.5, 16)}) + oggOK, err := os.ReadFile("testdata/vorbis.ogg") + require.NoError(t, err) + + garbage := bytes.Repeat([]byte{0xA5, 0x5A, 0x00, 0xFF}, 512) + + tests := []struct { + name string + format string + data []byte + failOnOpen bool + }{ + {name: "flac truncated mid-frame", format: mediaFLAC, data: flacOK[:len(flacOK)-2000]}, + {name: "flac magic only", format: mediaFLAC, data: []byte("fLaC"), failOnOpen: true}, + {name: "flac garbage", format: mediaFLAC, data: append([]byte("fLaC"), garbage...), failOnOpen: true}, + {name: "ogg magic only", format: mediaOGG, data: []byte("OggS"), failOnOpen: true}, + {name: "ogg garbage", format: mediaOGG, data: append([]byte("OggS"), garbage...), failOnOpen: true}, + {name: "ogg truncated headers", format: mediaOGG, data: oggOK[:200], failOnOpen: true}, + {name: "mp3 garbage", format: mediaMP3, data: append([]byte{0xFF, 0xFB}, garbage...), failOnOpen: true}, + {name: "mp3 id3 only", format: mediaMP3, data: []byte("ID3\x04\x00\x00\x00\x00\x00\x00"), failOnOpen: true}, + {name: "wav empty data", format: mediaWAV, data: []byte("RIFF\x00\x00\x00\x00WAVE"), failOnOpen: true}, + { + name: "mp4 no decoder", format: mediaMP4, failOnOpen: true, + data: []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src, openErr := openAudio(tt.format, tt.data) + if tt.failOnOpen { + require.Error(t, openErr) + + return + } + + require.NoError(t, openErr) + + _, decErr := decodeAudio(t.Context(), src, true, maxAudioSeconds) + require.ErrorIs(t, decErr, errDecode) + }) + } +} + +type panicSource struct{} + +func (panicSource) rate() int { return engineSampleRate } +func (panicSource) channels() int { return 1 } +func (panicSource) frames() int64 { return -1 } +func (panicSource) read([]int16) (int, error) { panic("decoder exploded") } + +type endlessSource struct{ rateHz int } + +func (e endlessSource) rate() int { return e.rateHz } +func (endlessSource) channels() int { return 1 } +func (endlessSource) frames() int64 { return -1 } +func (endlessSource) read(dst []int16) (int, error) { + clear(dst) + + return len(dst), nil +} + +func TestDecodeAudioBoundaries(t *testing.T) { + t.Parallel() + + t.Run("panic becomes error", func(t *testing.T) { + t.Parallel() + + _, err := decodeAudio(t.Context(), panicSource{}, true, maxAudioSeconds) + require.ErrorIs(t, err, errDecode) + assert.Contains(t, err.Error(), "decoder exploded") + }) + + t.Run("duration cap", func(t *testing.T) { + t.Parallel() + + _, err := decodeAudio(t.Context(), endlessSource{rateHz: 8000}, true, 2) + require.ErrorIs(t, err, errAudioLength) + }) + + t.Run("exactly at cap", func(t *testing.T) { + t.Parallel() + + media := buildWAV(wavSpec{tag: 1, bits: 16, channels: 1, rate: 8000}, toneSamples(8000, 2)) + src, err := openAudio(mediaWAV, media) + require.NoError(t, err) + + audio, err := decodeAudio(t.Context(), src, true, 2) + require.NoError(t, err) + assert.Equal(t, 2000, audio.millis) + }) + + t.Run("limit is four hours", func(t *testing.T) { + t.Parallel() + + assert.Equal(t, 14400, maxAudioSeconds) + }) +} + +type recordingEngine struct { + rates []int + sizes []int + mu sync.Mutex +} + +func (*recordingEngine) SupportsLanguage(string) bool { return true } + +func (e *recordingEngine) Recognize(_ context.Context, _ string, rate int, pcm []byte) ([]Word, error) { + e.mu.Lock() + defer e.mu.Unlock() + + e.rates = append(e.rates, rate) + e.sizes = append(e.sizes, len(pcm)) + + return []Word{{Text: "hi", Start: 0.1, End: 0.2, Confidence: 1}}, nil +} + +func TestRunPipelineDecodesContainers(t *testing.T) { + t.Parallel() + + oggOK, err := os.ReadFile("testdata/vorbis.ogg") + require.NoError(t, err) + + flac16 := encodeFLAC(t, 16000, 16, [][]int32{intTone(16000, 0.5, 16)}) + flacStereo := encodeFLAC(t, 16000, 16, [][]int32{intTone(16000, 0.5, 16), intTone(16000, 0.5, 16)}) + short := intTone(16000, 0.1, 16) + flac3ch := encodeFLAC(t, 16000, 16, [][]int32{short, short, short}) + wav24 := buildWAV(wavSpec{tag: 1, bits: 24, channels: 1, rate: 44100}, toneSamples(44100, 0.5)) + truncated := flac16[:len(flac16)-2000] + + tests := []struct { + name string + media []byte + format string + kind jobKind + wantFail string + wantSizes []int + sampleRate int32 + }{ + {name: "flac", media: flac16, format: "flac", kind: kindTranscription, wantSizes: []int{8000}}, + { + name: "flac stereo mono mix", media: flacStereo, format: "flac", kind: kindTranscription, + wantSizes: []int{8000}, + }, + { + name: "flac call analytics keeps channels", media: flacStereo, format: "flac", kind: kindCallAnalytics, + wantSizes: []int{8000, 8000}, + }, + {name: "wav24 resampled", media: wav24, format: "wav", kind: kindTranscription, wantSizes: []int{8000}}, + {name: "ogg", media: oggOK, format: "ogg", kind: kindTranscription}, + { + name: "ogg format mismatch", + media: oggOK, + format: "mp3", + kind: kindTranscription, + wantFail: failFormatMismatch, + }, + { + name: "flac rate mismatch", media: flac16, format: "flac", kind: kindTranscription, + sampleRate: 44100, wantFail: failSampleRate, + }, + { + name: "flac rate match", + media: flac16, + format: "flac", + kind: kindTranscription, + sampleRate: 16000, + wantSizes: []int{8000}, + }, + {name: "flac three channels", media: flac3ch, format: "flac", kind: kindTranscription, wantFail: failChannels}, + { + name: "flac truncated", + media: truncated, + format: "flac", + kind: kindTranscription, + wantFail: failUnsupportedFormat, + }, + { + name: "mp4 undecodable", media: []byte("\x00\x00\x00\x18ftypmp42\x00\x00\x00\x00"), format: "mp4", + kind: kindTranscription, wantFail: "cannot decode mp4 media", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + eng := &recordingEngine{} + deps := pipelineDeps{reader: filterMedia{"b/a": tt.media}, engine: eng, accountID: "123456789012"} + spec := jobSpec{ + Kind: tt.kind, Name: "j", Language: "en-US", MediaURI: "s3://b/a", MediaFormat: tt.format, + SampleRate: tt.sampleRate, + } + + out := runPipeline(t.Context(), deps, spec) + + if tt.wantFail != "" { + assert.Contains(t, out.failure, tt.wantFail) + assert.Empty(t, eng.sizes) + + return + } + + require.Empty(t, out.failure) + require.NotEmpty(t, out.files) + + for _, r := range eng.rates { + assert.Equal(t, engineSampleRate, r) + } + + if tt.wantSizes != nil { + require.Len(t, eng.sizes, len(tt.wantSizes)) + + for i, n := range tt.wantSizes { + assert.InDelta(t, n, eng.sizes[i]/2, 2) + } + } + }) + } +} + +func TestRunPipelineWithoutEngineValidatesHeaders(t *testing.T) { + t.Parallel() + + flac16 := encodeFLAC(t, 16000, 16, [][]int32{intTone(16000, 0.5, 16)}) + short := intTone(16000, 0.1, 16) + flac3ch := encodeFLAC(t, 16000, 16, [][]int32{short, short, short}) + adpcm := buildWAV(wavSpec{tag: 1, bits: 16, channels: 1, rate: 8000}, toneSamples(8000, 0.1)) + binary.LittleEndian.PutUint16(adpcm[20:], 2) + wav3ch := buildWAV(wavSpec{tag: 1, bits: 16, channels: 3, rate: 8000}, toneSamples(8000, 0.1)) + wav20 := buildWAV(wavSpec{tag: 1, bits: 16, channels: 1, rate: 8000}, toneSamples(8000, 0.1)) + binary.LittleEndian.PutUint16(wav20[34:], 20) + + tests := []struct { + name string + format string + wantFail string + media []byte + sampleRate int32 + }{ + {name: "valid flac", format: "flac", media: flac16}, + {name: "flac three channels", format: "flac", media: flac3ch, wantFail: failChannels}, + {name: "flac rate mismatch", format: "flac", media: flac16, sampleRate: 44100, wantFail: failSampleRate}, + {name: "placeholder flac completes", format: "flac", media: append([]byte("fLaC"), 0xFF, 0xFF)}, + {name: "placeholder mp3 completes", format: "mp3", media: []byte("ID3 placeholder media")}, + {name: "placeholder ogg completes", format: "ogg", media: []byte("OggS placeholder media")}, + {name: "wav adpcm completes", format: "wav", media: adpcm}, + {name: "wav 20 bit completes", format: "wav", media: wav20}, + {name: "wav adpcm three channels", format: "wav", media: wav3ch, wantFail: failChannels}, + {name: "wav adpcm rate mismatch", format: "wav", media: adpcm, sampleRate: 16000, wantFail: failSampleRate}, + { + name: "malformed wav", + format: "wav", + media: []byte("RIFF\x00\x00\x00\x00WAVEjunk"), + wantFail: failUnsupportedFormat, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + deps := pipelineDeps{reader: filterMedia{"b/a": tt.media}, accountID: "1"} + spec := jobSpec{ + Kind: kindTranscription, Name: "j", Language: "en-US", MediaURI: "s3://b/a", MediaFormat: tt.format, + SampleRate: tt.sampleRate, + } + out := runPipeline(t.Context(), deps, spec) + + if tt.wantFail != "" { + assert.Equal(t, tt.wantFail, out.failure) + + return + } + + assert.Empty(t, out.failure) + }) + } +} diff --git a/services/transcribe/call_analytics.go b/services/transcribe/call_analytics.go index 8b66f9caaf..2247475f16 100644 --- a/services/transcribe/call_analytics.go +++ b/services/transcribe/call_analytics.go @@ -395,6 +395,8 @@ func (b *InMemoryBackend) DeleteCallAnalyticsJob(jobName string) error { b.mu.Lock("DeleteCallAnalyticsJob") defer b.mu.Unlock() + b.cancelRunLocked(kindCallAnalytics, jobName) + if !b.callAnalyticsJobs.Delete(jobName) { return fmt.Errorf("%w: call analytics job %s not found", ErrNotFound, jobName) } diff --git a/services/transcribe/hostile_media_internal_test.go b/services/transcribe/hostile_media_internal_test.go new file mode 100644 index 0000000000..e797d80023 --- /dev/null +++ b/services/transcribe/hostile_media_internal_test.go @@ -0,0 +1,406 @@ +package transcribe + +import ( + "context" + "encoding/binary" + "fmt" + "math" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type countingSource struct { + served *int64 + rateHz int +} + +func (c countingSource) rate() int { return c.rateHz } +func (countingSource) channels() int { return 1 } +func (countingSource) frames() int64 { return -1 } +func (c countingSource) read(dst []int16) (int, error) { + clear(dst) + + *c.served += int64(len(dst)) + + return len(dst), nil +} + +type stalledSource struct{} + +func (stalledSource) rate() int { return engineSampleRate } +func (stalledSource) channels() int { return 1 } +func (stalledSource) frames() int64 { return -1 } +func (stalledSource) read([]int16) (int, error) { return 0, nil } + +func TestDecodeAudioBoundsOutput(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + rateHz int + }{ + {name: "one_hz_upsamples_16000x", rateHz: 1}, + {name: "native_rate", rateHz: engineSampleRate}, + {name: "high_rate", rateHz: 192000}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + var served int64 + + _, err := decodeAudio( + t.Context(), + countingSource{served: &served, rateHz: tt.rateHz}, + true, + maxAudioSeconds, + ) + require.ErrorIs(t, err, errAudioLength) + + producedBytes := served * engineSampleRate / int64(tt.rateHz) * pcmSampleBytes + assert.LessOrEqual( + t, + producedBytes, + int64(maxDecodedBytes)+decodeChunkFrames*engineSampleRate*pcmSampleBytes, + ) + }) + } +} + +func TestDecodeAudioStops(t *testing.T) { + t.Parallel() + + t.Run("cancelled_context", func(t *testing.T) { + t.Parallel() + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + + var served int64 + + _, err := decodeAudio(ctx, countingSource{served: &served, rateHz: engineSampleRate}, true, maxAudioSeconds) + require.ErrorIs(t, err, context.Canceled) + assert.Zero(t, served) + }) + + t.Run("no_progress", func(t *testing.T) { + t.Parallel() + + _, err := decodeAudio(t.Context(), stalledSource{}, true, maxAudioSeconds) + require.ErrorIs(t, err, errDecode) + }) +} + +func wavWithFmt(channels, rate, bits int, dataSize uint32, data []byte) []byte { + out := []byte("RIFF") + out = binary.LittleEndian.AppendUint32(out, 0xFFFFFFFF) + out = append(out, "WAVEfmt "...) + out = binary.LittleEndian.AppendUint32(out, 16) + out = binary.LittleEndian.AppendUint16(out, 1) + out = binary.LittleEndian.AppendUint16(out, uint16(channels)) + out = binary.LittleEndian.AppendUint32(out, uint32(rate)) + out = binary.LittleEndian.AppendUint32(out, 0) + out = binary.LittleEndian.AppendUint16(out, 0) + out = binary.LittleEndian.AppendUint16(out, uint16(bits)) + out = append(out, "data"...) + out = binary.LittleEndian.AppendUint32(out, dataSize) + + return append(out, data...) +} + +func TestHostileWAVHeaders(t *testing.T) { + t.Parallel() + + body := make([]byte, 64) + + tests := []struct { + name string + wav []byte + }{ + {name: "data_size_4gib", wav: wavWithFmt(1, 8000, 16, 0xFFFFFFFF, body)}, + {name: "zero_channels", wav: wavWithFmt(0, 8000, 16, 64, body)}, + {name: "zero_rate", wav: wavWithFmt(1, 0, 16, 64, body)}, + {name: "zero_bits", wav: wavWithFmt(1, 8000, 0, 64, body)}, + {name: "65535_channels", wav: wavWithFmt(65535, 8000, 16, 64, body)}, + {name: "rate_4g", wav: wavWithFmt(1, 0xFFFFFFFF, 16, 64, body)}, + {name: "rate_1", wav: wavWithFmt(1, 1, 16, 64, body)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src, err := openAudio(mediaWAV, tt.wav) + if err != nil { + require.ErrorIs(t, err, errDecode) + + return + } + + if src.channels() > dualChannel { + _, err = decodeAudio(t.Context(), src, false, maxAudioSeconds) + require.ErrorIs(t, err, errDecode) + + return + } + + _, err = decodeAudio(t.Context(), src, true, maxAudioSeconds) + require.NoError(t, err) + }) + } +} + +func TestFloatAndPCMConversion(t *testing.T) { + t.Parallel() + + f32 := func(vs ...float32) []byte { + var b []byte + for _, v := range vs { + b = binary.LittleEndian.AppendUint32(b, math.Float32bits(v)) + } + + return b + } + f64 := func(vs ...float64) []byte { + var b []byte + for _, v := range vs { + b = binary.LittleEndian.AppendUint64(b, math.Float64bits(v)) + } + + return b + } + + tests := []struct { + name string + in []byte + want []int16 + codec int + width int + }{ + { + name: "float32_specials", codec: wavFormatFloat, width: 4, + in: f32( + float32(math.NaN()), float32(math.Inf(1)), float32(math.Inf(-1)), 1e30, -1e30, 1, -1, 0, + ), + want: []int16{0, 32767, -32768, 32767, -32768, 32767, -32767, 0}, + }, + { + name: "float64_specials", codec: wavFormatFloat, width: 8, + in: f64(math.NaN(), math.Inf(1), math.Inf(-1), 2, 0.5), + want: []int16{0, 32767, -32768, 32767, 16384}, + }, + { + name: "pcm8_bias", codec: wavFormatPCM, width: 1, + in: []byte{0, 128, 255}, want: []int16{-32768, 0, 32512}, + }, + { + name: "pcm24_sign", codec: wavFormatPCM, width: 3, + in: []byte{0x00, 0x00, 0x80, 0xFF, 0xFF, 0x7F, 0xFF, 0xFF, 0xFF}, + want: []int16{-32768, 32767, -1}, + }, + { + name: "pcm32_extremes", codec: wavFormatPCM, width: 4, + in: []byte{0, 0, 0, 0x80, 0xFF, 0xFF, 0xFF, 0x7F}, + want: []int16{-32768, 32767}, + }, + { + name: "mulaw_reference", codec: wavFormatMuLaw, width: 1, + in: []byte{0xFF, 0x7F, 0x00, 0x80}, want: []int16{0, 0, -32124, 32124}, + }, + { + name: "alaw_reference", codec: wavFormatALaw, width: 1, + in: []byte{0xD5, 0x55, 0xAA, 0x2A}, want: []int16{8, -8, 32256, -32256}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + s := &wavSource{codec: tt.codec, width: tt.width} + got := make([]int16, 0, len(tt.want)) + + for off := 0; off < len(tt.in); off += tt.width { + got = append(got, s.sample(tt.in[off:off+tt.width])) + } + + assert.Equal(t, tt.want, got) + }) + } +} + +func TestResamplerMatchesReference(t *testing.T) { + t.Parallel() + + const frames = 96000 * 2 + + rates := []int{8000, 11025, 16000, 22050, 32000, 44100, 48000, 96000} + chunks := []int{1, 7, decodeChunkFrames, 100000} + + input := make([]int16, frames) + for i := range input { + input[i] = int16(20000 * math.Sin(float64(i)*0.01) * math.Cos(float64(i)*0.0007)) + } + + for _, rate := range rates { + for _, chunk := range chunks { + t.Run(fmt.Sprintf("%d_hz_chunk_%d", rate, chunk), func(t *testing.T) { + t.Parallel() + + n := frames * rate / 96000 + in := input[:n] + want := referenceResample(in, rate) + + r := newResampler(rate, engineSampleRate) + + var out []byte + + for off := 0; off < len(in); off += chunk { + for _, v := range in[off:min(off+chunk, len(in))] { + out = r.push(v, out) + } + } + + got := pcmInt16(out) + require.InDelta(t, len(want), len(got), 1, "rate %d chunk %d", rate, chunk) + + for i := range min(len(want), len(got)) { + require.InDelta(t, want[i], got[i], 1, "rate %d sample %d", rate, i) + } + }) + } + } +} + +func referenceResample(in []int16, rate int) []int16 { + step := float64(rate) / engineSampleRate + prefix := make([]float64, len(in)+1) + + for i, v := range in { + prefix[i+1] = prefix[i] + float64(v) + } + + area := func(x float64) float64 { + i := int(x) + if i >= len(in) { + return prefix[len(in)] + } + + return prefix[i] + float64(in[i])*(x-float64(i)) + } + + var out []int16 + + if step >= 1 { + for j := 0; float64(j+1)*step <= float64(len(in))+1e-6; j++ { + out = append(out, clampInt16((area(float64(j+1)*step)-area(float64(j)*step))/step)) + } + + return out + } + + for j := 0; ; j++ { + t := float64(j) * step + i := int(t) + + if i+1 > len(in)-1 { + return out + } + + out = append(out, clampInt16(float64(in[i])+(float64(in[i+1])-float64(in[i]))*(t-float64(i)))) + } +} + +//nolint:paralleltest // measures process-wide allocation +func TestMP3HostileHeaders(t *testing.T) { + tests := []struct { + name string + data []byte + }{ + {name: "id3_declares_256mib", data: append([]byte("ID3\x04\x00\x00\x7f\x7f\x7f\x7f"), make([]byte, 32)...)}, + {name: "free_format_frame", data: append([]byte{0xFF, 0xFB, 0x00, 0x40}, make([]byte, 4096)...)}, + {name: "all_ones", data: func() []byte { + b := make([]byte, 4096) + for i := range b { + b[i] = 0xFF + } + + return b + }()}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { //nolint:paralleltest // measures process-wide allocation + var before, after runtime.MemStats + + runtime.GC() + runtime.ReadMemStats(&before) + + src, err := openAudio(mediaMP3, tt.data) + if err == nil { + _, err = decodeAudio(t.Context(), src, true, maxAudioSeconds) + } + + runtime.ReadMemStats(&after) + + if err != nil { + require.ErrorIs(t, err, errDecode) + } + + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(8<<20)) + }) + } +} + +func patchFLACInfo(data []byte, rate, channels, bits, samples uint64) []byte { + out := append([]byte(nil), data...) + word := rate<<44 | (channels-1)<<41 | (bits-1)<<36 | samples + binary.BigEndian.PutUint64(out[18:26], word) + + return out +} + +func TestHostileFLACHeaders(t *testing.T) { + t.Parallel() + + base := encodeFLAC(t, 16000, 16, [][]int32{intTone(16000, 0.2, 16)}) + + tests := []struct { + name string + media []byte + }{ + {name: "samples_2_36", media: patchFLACInfo(base, 16000, 1, 16, 1<<36-1)}, + {name: "eight_channels", media: patchFLACInfo(base, 16000, 8, 16, 3200)}, + {name: "bits_32", media: patchFLACInfo(base, 16000, 1, 32, 3200)}, + {name: "bits_4", media: patchFLACInfo(base, 16000, 1, 4, 3200)}, + {name: "rate_max", media: patchFLACInfo(base, 1<<20-1, 1, 16, 3200)}, + {name: "rate_zero", media: patchFLACInfo(base, 0, 1, 16, 3200)}, + {name: "truncated_midframe", media: base[:len(base)/2]}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + src, err := openAudio(mediaFLAC, tt.media) + if err != nil { + require.ErrorIs(t, err, errDecode) + + return + } + + if src.channels() > dualChannel { + return + } + + _, err = decodeAudio(t.Context(), src, true, maxAudioSeconds) + if err != nil { + require.ErrorIs(t, err, errDecode) + } + }) + } +} diff --git a/services/transcribe/job_delete_cancels_test.go b/services/transcribe/job_delete_cancels_test.go new file mode 100644 index 0000000000..e22797e7f9 --- /dev/null +++ b/services/transcribe/job_delete_cancels_test.go @@ -0,0 +1,91 @@ +package transcribe_test + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/require" + + "github.com/blackbirdworks/gopherstack/services/transcribe" +) + +type cancelProbeEngine struct { + entered chan struct{} + cancelled chan struct{} +} + +func (cancelProbeEngine) SupportsLanguage(string) bool { return true } + +func (e cancelProbeEngine) Recognize(ctx context.Context, _ string, _ int, _ []byte) ([]transcribe.Word, error) { + close(e.entered) + <-ctx.Done() + close(e.cancelled) + + return nil, ctx.Err() +} + +func TestDeleteJobCancelsRecognition(t *testing.T) { + t.Parallel() + + tests := []struct { + start func(b *transcribe.InMemoryBackend) error + delete func(b *transcribe.InMemoryBackend) error + name string + }{ + { + name: "transcription", + start: func(b *transcribe.InMemoryBackend) error { + _, err := b.StartTranscriptionJob(&transcribe.TranscriptionJob{ + JobName: "j", LanguageCode: "en-US", MediaFormat: "wav", + Media: transcribe.Media{MediaFileURI: "s3://in/a.wav"}, + }) + + return err + }, + delete: func(b *transcribe.InMemoryBackend) error { return b.DeleteTranscriptionJob("j") }, + }, + { + name: "medical", + start: func(b *transcribe.InMemoryBackend) error { + _, err := b.StartMedicalTranscriptionJob(&transcribe.MedicalTranscriptionJob{ + MedicalTranscriptionJobName: "j", LanguageCode: "en-US", MediaFormat: "wav", + Specialty: "PRIMARYCARE", Type: "CONVERSATION", + Media: transcribe.Media{MediaFileURI: "s3://in/a.wav"}, OutputBucketName: "out", + }) + + return err + }, + delete: func(b *transcribe.InMemoryBackend) error { return b.DeleteMedicalTranscriptionJob("j") }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + eng := cancelProbeEngine{entered: make(chan struct{}), cancelled: make(chan struct{})} + b := transcribe.NewInMemoryBackend() + b.SetMediaReader(staticMedia{data: wavFile(1, 0.1)}) + b.SetS3Writer(&fakeS3{}) + b.SetEngine(eng) + t.Cleanup(func() { b.Shutdown(context.WithoutCancel(t.Context())) }) + + require.NoError(t, tt.start(b)) + + select { + case <-eng.entered: + case <-time.After(10 * time.Second): + t.Fatal("engine never started") + } + + require.NoError(t, tt.delete(b)) + + select { + case <-eng.cancelled: + case <-time.After(10 * time.Second): + t.Fatal("recognition kept running after the job was deleted") + } + }) + } +} diff --git a/services/transcribe/media.go b/services/transcribe/media.go index 17e3590c70..2712179486 100644 --- a/services/transcribe/media.go +++ b/services/transcribe/media.go @@ -164,6 +164,7 @@ type wavInfo struct { channels int bits int formatTag int + subTag int } const ( @@ -204,6 +205,12 @@ func parseWAV(data []byte) (wavInfo, error) { info.channels = int(binary.LittleEndian.Uint16(f[2:4])) info.sampleRate = int(binary.LittleEndian.Uint32(f[4:8])) info.bits = int(binary.LittleEndian.Uint16(f[14:16])) + info.subTag = 0 + + if info.formatTag == wavFormatExtensible && len(f) >= wavFmtExtMin { + info.subTag = int(binary.LittleEndian.Uint16(f[wavFmtExtSubTag:wavFmtExtMin])) + } + haveFmt = true case "data": if !haveFmt { @@ -221,45 +228,16 @@ func parseWAV(data []byte) (wavInfo, error) { return info, errBadWAV } -// isPCM16 reports whether the WAV holds 16-bit linear PCM the engine can consume. -func (w wavInfo) isPCM16() bool { - return (w.formatTag == wavFormatPCM || w.formatTag == wavFormatExtensible) && w.bits == pcmBits && w.channels > 0 +// codec is the effective format tag, resolving WAVE_FORMAT_EXTENSIBLE to its sub-format. +func (w wavInfo) codec() int { + if w.formatTag == wavFormatExtensible { + return w.subTag + } + + return w.formatTag } const ( pcmBits = 16 bitsPerByte = 8 ) - -// channelPCM de-interleaves 16-bit PCM into one mono stream per channel. -func (w wavInfo) channelPCM() [][]byte { - const sampleBytes = 2 - - frame := w.channels * sampleBytes - frames := len(w.pcm) / frame - out := make([][]byte, w.channels) - - for c := range out { - out[c] = make([]byte, 0, frames*sampleBytes) - } - - for i := range frames { - for c := range out { - off := i*frame + c*sampleBytes - out[c] = append(out[c], w.pcm[off], w.pcm[off+1]) - } - } - - return out -} - -// durationMillis is the playing time of the audio data. -func (w wavInfo) durationMillis() int { - if w.sampleRate == 0 || w.channels == 0 || w.bits == 0 { - return 0 - } - - bytesPerFrame := w.channels * max(w.bits/bitsPerByte, 1) - - return len(w.pcm) / bytesPerFrame * millisPerSecond / w.sampleRate -} diff --git a/services/transcribe/media_internal_test.go b/services/transcribe/media_internal_test.go index 7f41b8bddc..78e3a298d5 100644 --- a/services/transcribe/media_internal_test.go +++ b/services/transcribe/media_internal_test.go @@ -94,15 +94,10 @@ func TestParseWAV(t *testing.T) { info, err := parseWAV(stereo) require.NoError(t, err) - assert.True(t, info.isPCM16()) + assert.Equal(t, wavFormatPCM, info.codec()) assert.Equal(t, 16000, info.sampleRate) assert.Equal(t, 2, info.channels) - ch := info.channelPCM() - assert.Equal(t, [][]byte{{1, 0, 3, 0}, {2, 0, 4, 0}}, ch) - assert.Equal(t, []byte{1, 0}[:2], downmix([][]byte{{1, 0}, {1, 0}})[:2]) - assert.Equal(t, 0, info.durationMillis()) - for _, bad := range [][]byte{nil, []byte("RIFF"), []byte("RIFF\x00\x00\x00\x00WAVEdata\x00\x00\x00\x00")} { _, err = parseWAV(bad) require.ErrorIs(t, err, errBadWAV) diff --git a/services/transcribe/medical_transcription_jobs.go b/services/transcribe/medical_transcription_jobs.go index 5eaf1f33db..6f9328a1c0 100644 --- a/services/transcribe/medical_transcription_jobs.go +++ b/services/transcribe/medical_transcription_jobs.go @@ -188,6 +188,8 @@ func (b *InMemoryBackend) DeleteMedicalTranscriptionJob(jobName string) error { b.mu.Lock("DeleteMedicalTranscriptionJob") defer b.mu.Unlock() + b.cancelRunLocked(kindMedical, jobName) + if !b.medicalTranscriptionJobs.Delete(jobName) { return fmt.Errorf("%w: medical transcription job %s not found", ErrNotFound, jobName) } diff --git a/services/transcribe/pipeline.go b/services/transcribe/pipeline.go index 61470e7e91..60ff60fc50 100644 --- a/services/transcribe/pipeline.go +++ b/services/transcribe/pipeline.go @@ -2,7 +2,7 @@ package transcribe import ( "context" - "encoding/binary" + "errors" "fmt" "strings" "time" @@ -116,60 +116,93 @@ func inspectMedia(ctx context.Context, deps pipelineDeps, spec jobSpec) ([]byte, return data, format, outcome{} } -// checkWAV applies the header-derived checks; ok is false when the outcome is a failure. -func checkWAV(data []byte, spec jobSpec) (wavInfo, outcome, bool) { - info, err := parseWAV(data) +// openSource decodes the container header and applies the header-derived checks. Without a +// recognizer only a malformed WAV or a header that contradicts the job fails; an encoding the +// decoders cannot open leaves src nil and the job completes as it did before decoding existed. +func openSource(format string, data []byte, spec jobSpec, recognizing bool) (audioSource, outcome) { + src, err := openAudio(format, data) if err != nil { - return info, failf("%s", failUnsupportedFormat), false + if recognizing { + return nil, failf("%s", failUnsupportedFormat) + } + + return nil, legacyWAVCheck(format, data, spec) } - if info.channels > dualChannel { - return info, failf("%s", failChannels), false + if src.channels() > dualChannel { + return nil, failf("%s", failChannels) } - if spec.SampleRate != 0 && info.sampleRate != 0 && int(spec.SampleRate) != info.sampleRate { - return info, failf("%s", failSampleRate), false + if spec.SampleRate != 0 && src.rate() != 0 && int(spec.SampleRate) != src.rate() { + return nil, failf("%s", failSampleRate) } - return info, outcome{}, true + return src, outcome{} } -// recognize runs the engine over the WAV channels the job needs. -func recognize(ctx context.Context, deps pipelineDeps, spec jobSpec, info wavInfo, format string) ([][]Word, outcome) { +// legacyWAVCheck applies the WAV header checks that predate decoding to a file the decoders rejected. +func legacyWAVCheck(format string, data []byte, spec jobSpec) outcome { + if format != mediaWAV { + return outcome{} + } + + info, err := parseWAV(data) + + switch { + case err != nil: + return failf("%s", failUnsupportedFormat) + case info.channels > dualChannel: + return failf("%s", failChannels) + case spec.SampleRate != 0 && info.sampleRate != 0 && int(spec.SampleRate) != info.sampleRate: + return failf("%s", failSampleRate) + } + + return outcome{} +} + +// recognize decodes the media and runs the engine over the channels the job needs. +func recognize( + ctx context.Context, deps pipelineDeps, spec jobSpec, src audioSource, format string, +) ([][]Word, int, outcome) { eng := deps.engine if !eng.SupportsLanguage(spec.Language) { - return nil, failf("Language %s is not supported by the emulator speech engine.", spec.Language) + return nil, 0, failf("Language %s is not supported by the emulator speech engine.", spec.Language) } switch { case spec.ShowSpeakers: - return nil, failf("Speaker partitioning is not supported by the emulator speech engine.") + return nil, 0, failf("Speaker partitioning is not supported by the emulator speech engine.") case spec.Redaction: - return nil, failf("Content redaction is not supported by the emulator speech engine.") + return nil, 0, failf("Content redaction is not supported by the emulator speech engine.") case spec.PHI: - return nil, failf("Content identification is not supported by the emulator speech engine.") - case format != mediaWAV || !info.isPCM16(): - return nil, failf("The emulator speech engine can only transcribe 16-bit PCM WAV media; %s is not supported.", - formatLabel(format)) + return nil, 0, failf("Content identification is not supported by the emulator speech engine.") + case src == nil: + return nil, 0, failf("The emulator speech engine cannot decode %s.", formatLabel(format)) + } + + mono := !spec.IdentifyChannels && spec.Kind != kindCallAnalytics + + audio, err := decodeAudio(ctx, src, mono, maxAudioSeconds) + if errors.Is(err, errAudioLength) { + return nil, 0, failf("%s", failFileSize) } - streams := info.channelPCM() - if !spec.IdentifyChannels && spec.Kind != kindCallAnalytics { - streams = [][]byte{downmix(streams)} + if err != nil { + return nil, 0, failf("%s", failUnsupportedFormat) } - out := make([][]Word, 0, len(streams)) + out := make([][]Word, 0, len(audio.channels)) - for _, pcm := range streams { - words, err := eng.Recognize(ctx, spec.Language, info.sampleRate, pcm) - if err != nil { - return nil, failf("The emulator speech engine failed: %v", err) + for _, pcm := range audio.channels { + words, recErr := eng.Recognize(ctx, spec.Language, engineSampleRate, pcm) + if recErr != nil { + return nil, 0, failf("The emulator speech engine failed: %v", recErr) } out = append(out, words) } - return out, outcome{} + return out, audio.millis, outcome{} } func formatLabel(f string) string { @@ -180,26 +213,6 @@ func formatLabel(f string) string { return f + " media" } -// downmix averages 16-bit channels into one stream. -func downmix(streams [][]byte) []byte { - if len(streams) == 1 { - return streams[0] - } - - out := make([]byte, len(streams[0])) - - for i := 0; i+1 < len(out); i += 2 { - sum := 0 - for _, s := range streams { - sum += int(int16(binary.LittleEndian.Uint16(s[i:]))) //nolint:gosec // 16-bit sample reinterpretation - } - - binary.LittleEndian.PutUint16(out[i:], uint16(int16(sum/len(streams)))) //nolint:gosec // average fits int16 - } - - return out -} - // runPipeline reads and validates the media, recognises speech when an engine is installed and renders the documents. func runPipeline(ctx context.Context, deps pipelineDeps, spec jobSpec) outcome { data, format, bad := inspectMedia(ctx, deps, spec) @@ -208,25 +221,34 @@ func runPipeline(ctx context.Context, deps pipelineDeps, spec jobSpec) outcome { } var ( - info wavInfo + src audioSource channels [][]Word duration int ) - if format == mediaWAV { - var ok bool - if info, bad, ok = checkWAV(data, spec); !ok { + recognizing := deps.engine != nil && deps.reader != nil + + if decodable(format) { + if src, bad = openSource(format, data, spec, recognizing); bad.failure != "" { return bad } - duration = info.durationMillis() + if src != nil { + if n := src.frames(); n >= 0 { + duration = int(n * millisPerSecond / int64(src.rate())) + } + } } - if deps.engine != nil && deps.reader != nil { - if channels, bad = recognize(ctx, deps, spec, info, format); bad.failure != "" { + if recognizing { + var decoded int + + if channels, decoded, bad = recognize(ctx, deps, spec, src, format); bad.failure != "" { return bad } + duration = max(duration, decoded) + channels = applyVocabularyFilter(channels, spec.filterSet(ctx, deps), spec.FilterMethod) } @@ -416,6 +438,12 @@ func (b *InMemoryBackend) settleLocked(v jobView) { b.finishLocked(v, runPipeline(context.Background(), b.deps(), v.spec)) } +func (b *InMemoryBackend) cancelRunLocked(kind jobKind, name string) { + if cancel, ok := b.inflight[runKey(kind, name)]; ok { + cancel() + } +} + func (b *InMemoryBackend) launchRunLocked(v jobView) { key := runKey(v.spec.Kind, v.spec.Name) if _, running := b.inflight[key]; running { diff --git a/services/transcribe/testdata/README b/services/transcribe/testdata/README new file mode 100644 index 0000000000..e82da75591 --- /dev/null +++ b/services/transcribe/testdata/README @@ -0,0 +1,2 @@ +vorbis.ogg is testdata/test.ogg from github.com/jfreymuth/oggvorbis v1.0.5 +(MIT License, Copyright (c) 2016 Johann Freymuth), copied unchanged. diff --git a/services/transcribe/testdata/vorbis.ogg b/services/transcribe/testdata/vorbis.ogg new file mode 100644 index 0000000000..c930e06e53 Binary files /dev/null and b/services/transcribe/testdata/vorbis.ogg differ diff --git a/services/transcribe/transcription_jobs.go b/services/transcribe/transcription_jobs.go index a34e2b7a8c..027bdc00fe 100644 --- a/services/transcribe/transcription_jobs.go +++ b/services/transcribe/transcription_jobs.go @@ -191,6 +191,8 @@ func (b *InMemoryBackend) DeleteTranscriptionJob(jobName string) error { b.mu.Lock("DeleteTranscriptionJob") defer b.mu.Unlock() + b.cancelRunLocked(kindTranscription, jobName) + if !b.jobs.Delete(jobName) { return fmt.Errorf("%w: job %s not found", ErrNotFound, jobName) } diff --git a/services/transcribe/vorbis_guard.go b/services/transcribe/vorbis_guard.go new file mode 100644 index 0000000000..7be587d8ef --- /dev/null +++ b/services/transcribe/vorbis_guard.go @@ -0,0 +1,309 @@ +package transcribe + +import ( + "encoding/binary" + "errors" + "math" +) + +const ( + oggPageHeader = 27 + oggSegmentsAt = 26 + vorbisHeaders = 3 + vorbisMagicLen = 7 + vorbisCommentTyp = 3 + vorbisSetupTyp = 5 + vorbisCodebookID = 0x564342 + vorbisHeapBudget = 16 << 20 + bytesPerUint32 = 4 + huffmanBytes = 9 + maxLacing = 255 + bitIndexMask = 7 + lengthBitCount = 5 +) + +var errVorbisHeader = errors.New("hostile Vorbis header") + +// guardVorbisHeaders rejects comment and codebook headers that declare more memory than the file can back, +// because the Vorbis decoder allocates from header-declared counts before reading the data. +func guardVorbisHeaders(data []byte) error { + packets := oggHeaderPackets(data) + + for _, p := range packets { + if len(p) < vorbisMagicLen || string(p[1:vorbisMagicLen]) != "vorbis" { + continue + } + + var err error + + switch p[0] { + case vorbisCommentTyp: + err = guardVorbisComments(p[vorbisMagicLen:]) + case vorbisSetupTyp: + err = guardVorbisCodebooks(p[vorbisMagicLen:]) + } + + if err != nil { + return err + } + } + + return nil +} + +// oggHeaderPackets reassembles the first three packets of a logical stream. +func oggHeaderPackets(data []byte) [][]byte { + var ( + packets [][]byte + cur []byte + ) + + pos := 0 + + for pos+oggPageHeader <= len(data) && len(packets) < vorbisHeaders { + if string(data[pos:pos+4]) != "OggS" { + break + } + + nseg := int(data[pos+oggSegmentsAt]) + body := pos + oggPageHeader + nseg + + if body > len(data) { + break + } + + for _, lace := range data[pos+oggPageHeader : body] { + end := min(body+int(lace), len(data)) + cur = append(cur, data[body:end]...) + body = end + + if lace < maxLacing { + packets = append(packets, cur) + cur = nil + + if len(packets) == vorbisHeaders { + break + } + } + } + + pos = body + } + + return packets +} + +func guardVorbisComments(h []byte) error { + if len(h) < bytesPerUint32 { + return errVorbisHeader + } + + vendor := uint64(binary.LittleEndian.Uint32(h)) + if vendor+bytesPerUint32 > uint64(len(h)) { + return errVorbisHeader + } + + h = h[bytesPerUint32+vendor:] + if len(h) < bytesPerUint32 { + return errVorbisHeader + } + + count := uint64(binary.LittleEndian.Uint32(h)) + if count*bytesPerUint32 > uint64(len(h)) { + return errVorbisHeader + } + + return nil +} + +type vorbisBits struct { + data []byte + pos uint64 +} + +func (r *vorbisBits) left() uint64 { return uint64(len(r.data))*bitsPerByte - r.pos } + +func (r *vorbisBits) read(n uint) (uint64, bool) { + if uint64(n) > r.left() { + return 0, false + } + + var v uint64 + + for i := range n { + bit := (r.data[r.pos>>3] >> (r.pos & bitIndexMask)) & 1 + v |= uint64(bit) << i + r.pos++ + } + + return v, true +} + +func (r *vorbisBits) skip(n uint64) bool { + if n > r.left() { + return false + } + + r.pos += n + + return true +} + +func guardVorbisCodebooks(h []byte) error { + r := &vorbisBits{data: h} + + count, ok := r.read(bitsPerByte) + if !ok { + return errVorbisHeader + } + + var heap uint64 + + for range count + 1 { + cost, err := guardCodebook(r) + if err != nil { + return err + } + + heap += cost + if heap > vorbisHeapBudget { + return errVorbisHeader + } + } + + return nil +} + +// guardCodebook walks one codebook and returns the decoder's allocation for it. +func guardCodebook(r *vorbisBits) (uint64, error) { + const ( + patternBits = 24 + dimBits = 16 + entryBits = 24 + ) + + pattern, ok1 := r.read(patternBits) + dims, ok2 := r.read(dimBits) + entries, ok3 := r.read(entryBits) + ordered, ok4 := r.read(1) + + if !ok1 || !ok2 || !ok3 || !ok4 || pattern != vorbisCodebookID { + return 0, errVorbisHeader + } + + var lengthsOK bool + + if ordered == 0 { + lengthsOK = skipUnorderedLengths(r, entries) + } else { + lengthsOK = skipOrderedLengths(r, entries) + } + + if !lengthsOK { + return 0, errVorbisHeader + } + + lookup, err := guardLookup(r, entries, dims) + if err != nil { + return 0, err + } + + return entries*huffmanBytes + lookup, nil +} + +// guardLookup skips a codebook's value table and returns the memory the decoder builds from it. +func guardLookup(r *vorbisBits, entries, dims uint64) (uint64, error) { + const ( + kindBits = 4 + valueBitsBits = 4 + floatBits = 64 + ) + + kind, ok := r.read(kindBits) + if !ok || kind > 2 { + return 0, errVorbisHeader + } + + if kind == 0 { + return 0, nil + } + + if !r.skip(floatBits) { + return 0, errVorbisHeader + } + + valueBits, ok := r.read(valueBitsBits) + if !ok || !r.skip(1) || dims == 0 { + return 0, errVorbisHeader + } + + values := entries * dims + if kind == 1 { + values = lookup1Count(entries, dims) + } + + if !r.skip(values * (valueBits + 1)) { + return 0, errVorbisHeader + } + + return (entries*dims + values) * bytesPerUint32, nil +} + +func skipUnorderedLengths(r *vorbisBits, entries uint64) bool { + sparse, ok := r.read(1) + if !ok { + return false + } + + if sparse == 0 { + return r.skip(entries * lengthBitCount) + } + + for range entries { + flag, flagOK := r.read(1) + if !flagOK || flag == 1 && !r.skip(lengthBitCount) { + return false + } + } + + return true +} + +func skipOrderedLengths(r *vorbisBits, entries uint64) bool { + if !r.skip(lengthBitCount) { + return false + } + + var cur uint64 + + for cur < entries { + bits := uint(0) + for rest := entries - cur; rest > 0; rest >>= 1 { + bits++ + } + + n, ok := r.read(bits) + if !ok { + return false + } + + cur += n + } + + return true +} + +// lookup1Count is the largest v with v^dims <= entries. +func lookup1Count(entries, dims uint64) uint64 { + v := uint64(math.Pow(float64(entries), 1/float64(dims))) + + for math.Pow(float64(v+1), float64(dims)) <= float64(entries) { + v++ + } + + for v > 0 && math.Pow(float64(v), float64(dims)) > float64(entries) { + v-- + } + + return v +} diff --git a/services/transcribe/vorbis_guard_internal_test.go b/services/transcribe/vorbis_guard_internal_test.go new file mode 100644 index 0000000000..b3c89cf006 --- /dev/null +++ b/services/transcribe/vorbis_guard_internal_test.go @@ -0,0 +1,265 @@ +package transcribe + +import ( + "encoding/binary" + "os" + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func oggPages(packets ...[]byte) []byte { + var out []byte + + for seq, p := range packets { + var lacing []byte + + for rest := len(p); ; rest -= maxLacing { + if rest >= maxLacing { + lacing = append(lacing, maxLacing) + + if rest == maxLacing { + lacing = append(lacing, 0) + + break + } + + continue + } + + lacing = append(lacing, byte(rest)) + + break + } + + for len(lacing) > maxLacing { + lacing = lacing[:maxLacing] + } + + hdr := make([]byte, oggPageHeader, oggPageHeader+len(lacing)+len(p)) + copy(hdr, "OggS") + binary.LittleEndian.PutUint32(hdr[18:], uint32(seq)) + hdr[oggSegmentsAt] = byte(len(lacing)) + + page := append(append(hdr, lacing...), p...) + binary.LittleEndian.PutUint32(page[22:], oggCRC(page)) + out = append(out, page...) + } + + return out +} + +func oggCRC(page []byte) uint32 { + var crc uint32 + + for _, b := range page { + crc ^= uint32(b) << 24 + + for range 8 { + if crc&0x80000000 != 0 { + crc = crc<<1 ^ 0x04c11db7 + } else { + crc <<= 1 + } + } + } + + return crc +} + +type bitWriter struct { + buf []byte + used uint +} + +func (w *bitWriter) put(v uint64, n uint) { + for i := range n { + if w.used%8 == 0 { + w.buf = append(w.buf, 0) + } + + w.buf[len(w.buf)-1] |= byte((v>>i)&1) << (w.used % 8) + w.used++ + } +} + +func commentPacket(vendorLen, count uint32, body []byte) []byte { + p := append([]byte{vorbisCommentTyp}, "vorbis"...) + p = binary.LittleEndian.AppendUint32(p, vendorLen) + p = append(p, make([]byte, min(vendorLen, 4))...) + p = binary.LittleEndian.AppendUint32(p, count) + + return append(p, body...) +} + +func setupPacket(books func(w *bitWriter)) []byte { + w := &bitWriter{} + books(w) + + return append(append([]byte{vorbisSetupTyp}, "vorbis"...), w.buf...) +} + +func orderedBook(w *bitWriter, entries, dims uint64, lookup uint64) { + w.put(vorbisCodebookID, 24) + w.put(dims, 16) + w.put(entries, 24) + w.put(1, 1) + w.put(0, 5) + + for cur := uint64(0); cur < entries; { + bits := uint(0) + for rest := entries - cur; rest > 0; rest >>= 1 { + bits++ + } + + w.put(entries-cur, bits) + + cur = entries + } + + w.put(lookup, 4) + + if lookup != 0 { + w.put(0, 64) + w.put(0, 4) + w.put(0, 1) + } +} + +func TestGuardVorbisHeaders(t *testing.T) { + t.Parallel() + + ident := append([]byte{1}, "vorbis"...) + + tests := []struct { + name string + packets [][]byte + wantErr bool + }{ + { + name: "comment_count_4g", + packets: [][]byte{ident, commentPacket(4, 0xFFFFFFFF, nil)}, + wantErr: true, + }, + { + name: "comment_vendor_4g", + packets: [][]byte{ident, commentPacket(0xFFFFFFFF, 0, nil)}, + wantErr: true, + }, + { + name: "comment_ok", + packets: [][]byte{ident, commentPacket(4, 1, []byte{0, 0, 0, 0})}, + wantErr: false, + }, + { + name: "codebook_16m_entries_lookup2_dims_65535", + packets: [][]byte{ident, commentPacket(4, 0, nil), setupPacket(func(w *bitWriter) { + w.put(0, 8) + orderedBook(w, 1<<24-1, 65535, 2) + })}, + wantErr: true, + }, + { + name: "codebook_many_ordered_books", + packets: [][]byte{ident, commentPacket(4, 0, nil), setupPacket(func(w *bitWriter) { + w.put(255, 8) + + for range 256 { + orderedBook(w, 1<<24-1, 1, 0) + } + })}, + wantErr: true, + }, + { + name: "codebook_truncated", + packets: [][]byte{ident, commentPacket(4, 0, nil), setupPacket(func(w *bitWriter) { + w.put(0, 8) + w.put(vorbisCodebookID, 24) + })}, + wantErr: true, + }, + { + name: "codebook_small_ok", + packets: [][]byte{ident, commentPacket(4, 0, nil), setupPacket(func(w *bitWriter) { + w.put(0, 8) + orderedBook(w, 16, 2, 1) + })}, + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + err := guardVorbisHeaders(oggPages(tt.packets...)) + if tt.wantErr { + require.ErrorIs(t, err, errVorbisHeader) + + return + } + + require.NoError(t, err) + }) + } +} + +//nolint:paralleltest // measures process-wide allocation +func TestOpenOGGRejectsHostileHeaderCheaply(t *testing.T) { + ident := append([]byte{1}, "vorbis"...) + data := oggPages(ident, commentPacket(4, 0xFFFFFFFF, nil)) + + var before, after runtime.MemStats + + runtime.GC() + runtime.ReadMemStats(&before) + + _, err := openAudio(mediaOGG, data) + + runtime.ReadMemStats(&after) + + require.ErrorIs(t, err, errDecode) + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(4<<20)) +} + +func TestGuardAcceptsRealVorbis(t *testing.T) { + t.Parallel() + + data, err := os.ReadFile("testdata/vorbis.ogg") + require.NoError(t, err) + require.NoError(t, guardVorbisHeaders(data)) +} + +func validIdent() []byte { + p := append([]byte{1}, "vorbis"...) + p = binary.LittleEndian.AppendUint32(p, 0) + p = append(p, 1) + p = binary.LittleEndian.AppendUint32(p, engineSampleRate) + p = append(p, make([]byte, 12)...) + p = append(p, 0xB8, 1) + + return p +} + +//nolint:paralleltest // measures process-wide allocation +func TestOpenOGGRejectsHostileCodebookCheaply(t *testing.T) { + setup := setupPacket(func(w *bitWriter) { + w.put(0, 8) + orderedBook(w, 1<<24-1, 65535, 2) + }) + data := oggPages(validIdent(), commentPacket(4, 0, nil), setup) + + var before, after runtime.MemStats + + runtime.GC() + runtime.ReadMemStats(&before) + + _, err := openAudio(mediaOGG, data) + + runtime.ReadMemStats(&after) + + require.ErrorIs(t, err, errDecode) + assert.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(4<<20)) +} diff --git a/test/guards/weak_hash_guard_test.go b/test/guards/weak_hash_guard_test.go index b92881cc66..9625710d7a 100644 --- a/test/guards/weak_hash_guard_test.go +++ b/test/guards/weak_hash_guard_test.go @@ -25,7 +25,9 @@ func allowedWeakHashFiles() map[string]string { "services/neptune/sparql/funcs_hash.go": "SPARQL 1.1 MD5()/SHA1() builtin functions", // Entra identifies certificates by SHA-1 thumbprint (JWS x5t, RFC 7515 4.1.7; keyCredential.customKeyIdentifier); an // identifier match, never a credential. - "services/azuregraph/certauth.go": "Entra x5t / customKeyIdentifier SHA-1 certificate thumbprint parity", + "services/azuregraph/certauth.go": "Entra x5t / customKeyIdentifier SHA-1 certificate thumbprint parity", + "services/azurearm/rp_logic_cert.go": "Logic client assertion x5t SHA-1 certificate thumbprint (RFC 7515)", + "services/azurearm/rp_apim_mgmt.go": "API Management certificate SHA-1 thumbprint", // Azure Blob Content-MD5 headers are the base64 MD5 of the body; integrity checksum, never a credential. "services/azureblob/handler_cond.go": "Azure Blob Content-MD5 header parity", // Identity Platform TOTP second factors are RFC 6238 HMAC-SHA1 (the API reports hashingAlgorithm SHA1); a one-time