swaggo / http-swagger

Default net/http wrapper to automatically generate RESTful API documentation with Swagger 2.0.
MIT License
427 stars 73 forks source link

Data race in `Handler`, modifies global from `swaggo/files` package but `sync.Once` protection is function scoped #78

Open mafredri opened 1 year ago

mafredri commented 1 year ago

As per title, the Handler has a data race in assigning Prefix due to the sync.Once being function scoped and Prefix existing in the swaggo/files package.

The problematic code: https://github.com/swaggo/http-swagger/blob/c8d62bfd8fdb3c72864adcf90b329a49a97bf7d6/swagger.go#L157-L159

This means that any reads to files.Handler.Prefix are globally unsafe across all swaggo packages.

The race can be avoided by only ever invoking one handler. This is not very likely to happen in practice, but problematic in tests. The way it's written also unfortunately means it's impossible to serve on two different endpoints (just an observed behavior, not a requirement).

OrkhanAlikhanov commented 11 months ago

This happens in practice as well. I have 2 routes defined for 2 different swaggers files. /swagger/*any and /swagger-swe/*any and I pass different handlers for them httpSwagger.Handler() and httpSwagger.Handler(httpSwagger.InstanceName("swe")). However only one of them works.

OrkhanAlikhanov commented 11 months ago

The same bug in gin-swagger package too: https://github.com/swaggo/gin-swagger/issues/225 https://github.com/swaggo/gin-swagger/issues/234