Skip to content

update: Api without authen#163

Merged
thanglp163 merged 1 commit intodevfrom
hotfix-public-certificate_thang
Aug 27, 2025
Merged

update: Api without authen#163
thanglp163 merged 1 commit intodevfrom
hotfix-public-certificate_thang

Conversation

@thanglp163
Copy link
Copy Markdown
Collaborator

@thanglp163 thanglp163 commented Aug 27, 2025

Summary by CodeRabbit

  • New Features

    • Viewing a certificate by its ID no longer requires signing in. This enables direct, shareable links to certificate pages for easier access by recipients and third parties.
    • Users can quickly verify certificate details without creating an account or logging in.
  • Security

    • Only the certificate view endpoint is now publicly accessible; all other certificate actions and routes retain their existing authentication and authorization requirements.

@thanglp163 thanglp163 self-assigned this Aug 27, 2025
@vercel
Copy link
Copy Markdown

vercel bot commented Aug 27, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
neurolearn-backend Ready Ready Preview Comment Aug 27, 2025 11:58am

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Aug 27, 2025

Walkthrough

The GET /:id route in src/routes/certificate.route.ts was changed to remove the isAuthenticated middleware, making the certificate retrieval endpoint publicly accessible. The route handler remains the same; no other routes or middleware configurations were modified.

Changes

Cohort / File(s) Summary
Certificate route auth change
src/routes/certificate.route.ts
Removed isAuthenticated from router.get('/:id', ...), leaving the handler getCertificateById(req, res).catch(next) intact. No other routes changed.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Client
  participant Router as Express Router
  participant Handler as getCertificateById

  rect rgba(200,230,255,0.25)
  note over Client,Handler: Before (with auth)
  participant Auth as isAuthenticated
  Client->>Router: GET /certificate/:id
  Router->>Auth: Verify session/token
  alt Auth OK
    Router->>Handler: getCertificateById(req)
    Handler-->>Router: res
    Router-->>Client: 200 OK / data
  else Auth Fail
    Auth-->>Client: 401/403
  end
  end

  rect rgba(200,255,200,0.25)
  note over Client,Handler: After (public route)
  Client->>Router: GET /certificate/:id
  Router->>Handler: getCertificateById(req)
  Handler-->>Router: res
  Router-->>Client: 200 OK / data or 4xx/5xx
  end
Loading

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~2 minutes

Possibly related PRs

  • feat: api Certificate #47 — Adjusts authentication for the same GET /:id route in src/routes/certificate.route.ts, but in the opposite direction (adds isAuthenticated), directly related to this change.

Poem

A hop, a skip—no guard at the gate,
The cert now greets both early and late.
Keys set aside, the path is clear,
Fetch by id, the bytes appear.
Thump-thump! says bunny, light and free—
One less lock, same data spree. 🥕✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hotfix-public-certificate_thang

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@thanglp163 thanglp163 merged commit 1daf32c into dev Aug 27, 2025
4 of 5 checks passed
Copy link
Copy Markdown

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d1d40a5 and 07dccbc.

📒 Files selected for processing (1)
  • src/routes/certificate.route.ts (1 hunks)

Comment on lines +9 to 11
router.get('/:id', (req, res, next) => {
getCertificateById(req, res).catch(next);
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Public GET /:id can leak PII and enable ID enumeration—add validation, rate limiting, and ensure sanitized response.

If this endpoint is intentionally public, harden it:

  • Validate :id format to reject garbage/enumeration attempts.
  • Add a small per-IP rate limit.
  • Ensure getCertificateById returns only public-safe fields (no email, phone, user object, etc.). If owner-only fields exist, introduce a getPublicCertificateById serializer or gate via certificate.isPublic or a short-lived signed token.

Apply this minimal route hardening (keeps it public) and add helpers shown below:

-router.get('/:id', (req, res, next) => {
-  getCertificateById(req, res).catch(next);
-});
+router.get(
+  '/:id',
+  validateCertificateIdParam,
+  publicCertificateLimiter,
+  (req, res, next) => {
+    getCertificateById(req, res).catch(next);
+  }
+);

Add these helpers near the top of the file:

import rateLimit from 'express-rate-limit';

const publicCertificateLimiter = rateLimit({
  windowMs: 60_000,
  max: 60,
  standardHeaders: true,
  legacyHeaders: false,
});

const validateCertificateIdParam: express.RequestHandler = (req, res, next) => {
  const { id } = req.params as { id: string };
  // Adjust regex if IDs are UUIDs instead of Mongo ObjectIds
  if (!/^[0-9a-fA-F]{24}$/.test(id)) {
    return res.status(400).json({ message: 'Invalid certificate id' });
  }
  next();
};

Option (if sensitive fields exist): introduce a public-safe controller and switch the route handler:

-  (req, res, next) => {
-    getCertificateById(req, res).catch(next);
-  }
+  (req, res, next) => {
+    getPublicCertificateById(req, res).catch(next);
+  }

Verification script to confirm no PII is returned by the public handler:

I can draft a getPublicCertificateById serializer (whitelisting fields) or wire a signed-token gate if needed.


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate controller implementation
rg -nP -C3 --type ts '\bgetCertificateById\b' src | sed -n '1,200p'

# Inspect for potentially sensitive fields in the response payload
rg -nP --type ts -C2 '\bres\.(json|send)\s*\(' src/controllers | sed -n '1,200p'
rg -nP --type ts -C2 '\b(email|phone|address|dob|dateOfBirth|user|profile)\b' src/controllers/certificate.controller.ts || true

# Look for populate/select patterns that might pull user data
rg -nP --type ts -C2 '\bpopulate\(|select\(|projection\b' src/controllers/certificate.controller.ts || true

Length of output: 6361


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the implementation of getCertificateById including its response handling
sed -n '1,200p' src/controllers/certificate.controller.ts

Length of output: 3459


Harden public GET /:id to prevent PII exposure and ID enumeration

The current handler

router.get('/:id', (req, res, next) => {
  getCertificateById(req, res).catch(next);
});

populates and returns the user’s email and allows unlimited requests against any ObjectId.

Please address the following critical issues:

• src/routes/certificate.route.ts (lines 9–11)
– Add a lightweight UUID/ObjectId‐format validator middleware to catch malformed IDs before invoking the controller.
– Apply a per‐IP rate limiter (e.g. 60 requests/minute) to throttle enumeration attempts.

• src/controllers/certificate.controller.ts (lines 12–16)
– Remove PII from public responses. The existing populate('user', 'name email') leaks email.
– Introduce a getPublicCertificateById that whitelists only non‐sensitive fields (e.g. certificate ID, course title, issue date), omitting email/phone/address.

Suggested diff for route hardening:

-import express from 'express';
+import express from 'express';
+import rateLimit from 'express-rate-limit';
+import { validateObjectIdParam } from '../middlewares/validateObjectIdParam';
 
 router.get('/:id', (req, res, next) => {
   getCertificateById(req, res).catch(next);
 });
 router.get(
-  '/:id',
-  (req, res, next) => {
-    getCertificateById(req, res).catch(next);
-  }
+  '/:id',
+  validateObjectIdParam('id'),
+  rateLimit({ windowMs: 60_000, max: 60 }),
+  (req, res, next) => {
+    getPublicCertificateById(req, res).catch(next);
+  }
 );

And sketch of getPublicCertificateById in src/controllers/certificate.controller.ts:

export const getPublicCertificateById = async (req: Request, res: Response) => {
  const { id } = req.params;
  // (ID format already validated by middleware)

  const cert = await Certificate.findById(id)
    .populate('course', 'title');
  if (!cert) return res.status(404).json({ message: 'Not found' });

  // Only expose non-PII fields
  const publicCert = {
    id: cert._id,
    course: cert.course.title,
    issuedAt: cert.issuedAt,
    // …other safe fields
  };

  res.status(200).json(publicCert);
};

These changes are critical to avoid leaking emails and to thwart brute-force enumeration of certificate IDs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant