Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issueid #231004 feat:play youtube help video in mylearning iframe #219

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 30 additions & 48 deletions src/components/Assesment/Assesment.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -647,14 +647,38 @@ const Assesment = ({ discoverStart }) => {

const { virtualId } = useSelector((state) => state.user);

const [isVideoOpen, setIsVideoOpen] = useState(false);

const handleOpenVideo = () => {
setIsVideoOpen(true);
};
if (process.env.REACT_APP_SHOW_HELP_VIDEO === "true") {
let allowedOrigins = [];
try {
allowedOrigins = JSON.parse(
process.env.REACT_APP_PARENT_ORIGIN_URL || "[]"
);
} catch (error) {
console.error(
"Invalid JSON format in REACT_APP_PARENT_ORIGIN_URL:",
error
);
}

const parentOrigin =
window?.location?.ancestorOrigins?.[0] || window.parent.location.origin;

const handleCloseVideo = () => {
setIsVideoOpen(false);
if (allowedOrigins.includes(parentOrigin)) {
try {
window.parent.postMessage(
{
message: "help-video-link",
},
parentOrigin
);
} catch (error) {
console.error("Error sending postMessage:", error);
}
} else {
console.warn(`Parent origin "${parentOrigin}" is not allowed.`);
}
}
Comment on lines +651 to +681
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

🛠️ Refactor suggestion

Security vulnerability: Multiple instances of unrestricted postMessage usage found

The verification revealed several security issues in the codebase:

  • src/components/DiscoverSentance/DiscoverSentance.jsx:104-110: Unrestricted postMessage with wildcard origin
  • src/components/Assesment/Assesment.jsx:352: Unrestricted postMessage with wildcard origin
  • src/views/Practice/Practice.jsx:125-131: Unrestricted postMessage with wildcard origin
  • src/views/Practice/Practice.jsx:763: Unrestricted postMessage with wildcard origin

The original review comment's security concerns are valid and even more critical now, as we've found multiple instances of unsafe cross-origin communication using wildcard origins ("*"). All these locations need the same origin verification pattern proposed in the review.

🔗 Analysis chain

Enhance security and error handling in cross-origin communication

The implementation has good security measures but could be strengthened further:

  1. Origin verification could be more robust
  2. Error handling could be more specific
  3. Environment variables should be validated at startup

Apply these improvements:

 const handleOpenVideo = () => {
   if (process.env.REACT_APP_SHOW_HELP_VIDEO === "true") {
     let allowedOrigins = [];
     try {
       allowedOrigins = JSON.parse(
         process.env.REACT_APP_PARENT_ORIGIN_URL || "[]"
       );
+      if (!Array.isArray(allowedOrigins)) {
+        throw new Error('REACT_APP_PARENT_ORIGIN_URL must be a JSON array');
+      }
     } catch (error) {
       console.error(
         "Invalid JSON format in REACT_APP_PARENT_ORIGIN_URL:",
         error
       );
+      return;
     }

     const parentOrigin =
       window?.location?.ancestorOrigins?.[0] || window.parent.location.origin;
+    
+    // Validate origin format
+    try {
+      new URL(parentOrigin);
+    } catch {
+      console.error(`Invalid parent origin format: ${parentOrigin}`);
+      return;
+    }

     if (allowedOrigins.includes(parentOrigin)) {
       try {
         window.parent.postMessage(
           {
             message: "help-video-link",
+            timestamp: Date.now(), // Add timestamp for message validation
           },
           parentOrigin
         );
       } catch (error) {
-        console.error("Error sending postMessage:", error);
+        console.error("Failed to send postMessage:", {
+          error: error.message,
+          parentOrigin,
+          timestamp: new Date().toISOString()
+        });
       }
     } else {
-      console.warn(`Parent origin "${parentOrigin}" is not allowed.`);
+      console.error(`Security violation: Unauthorized parent origin "${parentOrigin}"`);
     }
   }
 };

Consider implementing these additional security measures:

  1. Add message versioning for better compatibility
  2. Implement a message acknowledgment mechanism
  3. Add rate limiting for postMessage calls
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify if there are any other postMessage calls without origin verification
ast-grep --pattern 'window.parent.postMessage($$$, "*")'

# Check for potential security issues in postMessage usage
rg -n "postMessage.*\*" --type js

Length of output: 1485

};

const navigate = useNavigate();
Expand Down Expand Up @@ -855,48 +879,6 @@ const Assesment = ({ discoverStart }) => {
</Box>
</MainLayout>
)}
{/* Video Modal */}
<Dialog
open={isVideoOpen}
onClose={handleCloseVideo}
maxWidth="lg"
fullWidth
>
<Box
sx={{
position: "relative",
width: "100%",
paddingTop: "56.25%", // Maintain 16:9 aspect ratio
backgroundColor: "black", // Optional: Ensure a dark background
}}
>
<iframe
src={process.env.REACT_APP_SHOW_HELP_VIDEO_LINK}
title="YouTube video"
frameBorder="0"
allow="autoplay; encrypted-media"
allowFullScreen
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
}}
/>
</Box>
<IconButton
onClick={handleCloseVideo}
sx={{
position: "absolute",
top: 8,
right: 8,
zIndex: 1,
}}
>
<CloseIcon />
</IconButton>
</Dialog>
</>
);
};
Expand Down