openapi-filter icon indicating copy to clipboard operation
openapi-filter copied to clipboard

Inverse filtered documents do not include main level security definitions

Open duuri-mollinen opened this issue 9 months ago • 1 comments

Hi! 👋

Firstly, thanks for your work on this project! 🙂

Today I used patch-package to patch [email protected] for the project I'm working on.

Inverse filtered paths with following flags produce an non valid api document that does not include the securitySchemes under to components when there are active security definitions under the paths->path->method structure

-i --valid --strip --servers

Here is the diff that solved my problem:

diff --git a/node_modules/openapi-filter/index.js b/node_modules/openapi-filter/index.js
index dd1f690..d342663 100644
--- a/node_modules/openapi-filter/index.js
+++ b/node_modules/openapi-filter/index.js
@@ -139,10 +139,40 @@ function filter(obj,options) {
         if (options.servers && !filtered.servers && Array.isArray(src.servers)) {
             filtered.servers = src.servers;
         }
+        const activeSecuritySchemes= 
+        (src.paths?Object.keys(src.paths):[])
+            .flatMap(pathUrl =>src.paths[pathUrl])
+            .flatMap(pathElement => Object.keys(pathElement)
+            .flatMap(method =>pathElement[method]))
+            .filter(path => Object.keys(path).filter(value => options.flags.includes(value)))
+            .flatMap(path =>{
+                if (!filtered.security && Array.isArray(path.security)) {
+                    return path.security.flatMap(securityItem => Object.keys(securityItem));
+                }else{
+                    return [];
+                }
+            })
+            .filter(filterUnique)
+
+        // OAS2
+        if (src.securityDefinitions) {
+            filtered.securityDefinitions = Object.fromEntries(Object.entries(src.securityDefinitions).filter(([key]) => activeSecuritySchemes.includes(key)));
+        }
+        // OAS3
+        if (src.components && src.components.securitySchemes) {
+            if(!filtered.components){
+                filtered.components ={};
+            }
+            filtered.components.securitySchemes = Object.fromEntries(Object.entries(src.components.securitySchemes).filter(([key]) => activeSecuritySchemes.includes(key)));
+        }
     }
     return (options.inverse ? filtered : src);
 }
 
+function filterUnique(value, index, array) {
+    return array.indexOf(value) === index;
+  }
+
 module.exports = {
     filter : filter
 };

This issue body was partially generated by patch-package.

duuri-mollinen avatar Sep 21 '23 08:09 duuri-mollinen

Thanks, can patch-package produce PRs?

MikeRalphson avatar Oct 15 '23 13:10 MikeRalphson